They have a couple of ways.
1. Nielson families.
Certain families are chosen by demographic and given a device that tracks their viewing habits (In the old days they had to keep a viewing journal. ) Each family respresents a certain percentage of the viewing public.
2. Telephone polling.
They call a statistically significant number of people and ask them about their veiwing habits.