Sorting view results by the number of matched arguments (contextual filters) I have nodes with tags on them. I also have a view of nodes with a contextual filter that can take multiple tags. I have it set to get nodes that match any, rather than all.

So imagine I have three nodes, Lorem, Ipsum, and Dolor. They have the following tags:

Lorem: foo, bar, baz
Ipsum: foo, bar
Dolor: foo

When the contextual filter "foo" is passed, of course all three come up. When "foo" and "bar" are both passed, all three also come up. Currently, they come up in no particular order, so passing "foo" and "bar" might give me this (depending on my other filters): 


Dolor
Lorem
Ipsum


I want to sort by number of matched items, so passing "foo" and "bar" will bring them up in the order Lorem, Ipsum, Dolor or possibly Ipsum, Lorem, Dolor, but never with Dolor first. And if I pass all three terms I'd expect to see the only the order Lorem, Ipsum, Dolor. 

This seems like a common thing to need, and yet searching has not yielded a ready-made solution. How would one go about implementing this with Views 3 in Drupal 7?
Following is one way to achieve the specified ordering


Add a relationship to taxonomy terms.





Turn on aggregation
Set the sort criteria to COUNT DISTINCT of taxonomy term reference field.