If a user visits
demo.example.com, does that count as having visited the site
example.com? Does the Alexa ranking apply to the sub-domain or the primary domain?
No, a sub domain is a sub domain and treated as it's own entity. WWW is essentially a sub domain which is what many websites reside under by default unless they choose to display URL's without WWW.
Alexa however, will consolidate all sub domains under the primary domain and as such, will offer an Alexa traffic rank the same across any pages under that domain, including any sub domains.
You may find this useful, taken from Alexa's help pages:-
Traffic is computed for sites, which are typically defined at the domain level. For example, the Web hosts www.msn.com, carpoint.msn.com and slate.msn.com are all treated as part of the same site, because they all reside on the same domain, msn.com. An exception is blogs or personal home pages, which are treated separately if they can be automatically identified as such from the URLs in question. Also, sites which are found to be serving the same content (mirrors) are generally counted together as the same site.