Answer:
A sample of people with a demographic representative of the population is selected to provide data, and they either keep a diary of the shows they watch and report them, or they are provided with a device connected to their TV that monitors, records, and reports their television viewing behavior. The rest is basic statistical methods.
http://en.wikipedia.org/wiki/Nielsen_ratings