Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

8
  • 12
    I don't think this works if you have dupes, particularly a lot of dupes, in your data. You can't guarantee the row_numbers will line up. You can get some really crazy answers for your median, or even worse, no median at all. Commented Oct 5, 2010 at 23:58
  • 27
    That's why having a disambiguator (SalesOrderId in the code example above) is important, so you can ensure that the order of result-set rows is consistent both backwards and forwards. Often a unique primary key makes an ideal disambiguator because it's available without a separate index lookup. If there's no disambiguation column available (for example, if the table has no uniquifying key), then another approach must be used to calculate median, because as you correctly point out, if you can't guarantee that DESC row numbers are mirror images of ASC row numbers, then results are unpredictable. Commented Oct 6, 2010 at 18:24
  • 4
    Thanks, when switching the columns to my DB, I dropped the disambiguator, thinking it wasn't relevant. In that case, this solution works really really well. Commented Oct 10, 2010 at 3:10
  • 8
    I suggest adding a comment to the code itself, describing the need for the disambiguator.
    – hoffmanc
    Commented May 23, 2012 at 14:27
  • 5
    Awesome! long have i known its importance but now i can give it a name... the disambiguator! Thank you Justin!
    – CodeMonkey
    Commented Dec 19, 2013 at 15:56