How to write“greatest n per group” type query, but with additional conditions?

强颜欢笑 提交于 2019-12-04 07:09:05

This requires some attention where to put the condition (to where or to on?) so that you don't get tricked :-) You need to add the condition for t1 to where clause and for t2 to on clause:

SELECT t1.type, t1.name, t1.value
FROM mytable t1
LEFT JOIN mytable t2 ON t1.type = t2.type AND t1.value > t2.value 
    AND t2.popularity > 3 /* here */
WHERE t2.value IS NULL 
    AND t1.popularity > 3 /* and here */

Haven't tested it, but it should work.

Attempt for an explanation: the condition in where clause affects which elements you consider as potential elements with lowest value. Whereas the condition in on clause affects the linkage: to what other elements you want to compare it? It defines the group within which you compare. Technically, it has an impact on when t2.* will be NULL. Had you given the condition on t2.popularity to where clause instead, you would not receive any NULLs (i.e. not find elements w/lowest value) for groups where the lowest elements have low popularity.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!