当前位置: 代码迷 >> Sql Server >> 分析一条sql话语的意思-
  详细解决方案

分析一条sql话语的意思-

热度:81   发布时间:2016-04-27 10:53:02.0
分析一条sql语句的意思----------------
是mysql的

demo 表name val两列 按name分组 取分组后每组的前两个值 
下面的sql语句是正确的,我有试过,就是不懂它的意思
求解。。。。。。
SQL code
select a.* from demo a where 2 > ( select count(*) from demo where name = a.name and val > a.val ) 


这where 2>是啥意思,这条语句给分析下

------解决方案--------------------
select a.*,(select count(*) from demo where name = a.name and val > a.val) as col3
 from demo a 
试试这个,实际上按组排序,取序号小于2的就是每组前两个。
------解决方案--------------------
如果你这样看着不明白,那你看下面的
SQL code
--1select a.*,(select count(*) from demo where name = a.name and val > a.val )from demo a where 2 > ( select count(*) from demo where name = a.name and val > a.val ) --2select * from (select a.*,(select count(*) from demo where name = a.name and val > a.val ) as cnt) t where cnt >2
------解决方案--------------------
就是说 a 表中的每一行 与 demo 表比较 :
 name = a.name and val > a.val 这个是关联条件
这个
select count(*) from demo where name = a.name and val > a.val
在name相同的情况下,返回当整张表VAL比当前行VAL大的个数
  相关解决方案