在SQL中是否有办法通过按顺序检查条件来选择特定行?
条件:选择1 FC,最小(状态),最大(版本),最大(CD),最大(MD)
表数据:
FC Status Version CD MD
1 999 23 20 13
1 500 10 22 15
1 400 23 19 11
1 500 15 18 9
1 400 19 17 12
1 400 19 16 13
1 400 23 17 30
输出应为:
FC Status Version CD MD
1 400 23 19 11
答案 0 :(得分:8)
是。使用TOP
和ORDER BY
:
select top 1 t.*
from t
order by status asc, version desc, cd desc, md desc;
如果您想按FC
执行此操作,请使用row_number()
:
select t.*
from (select t.*,
row_number() over (partition by fc
order by status asc, version desc, cd desc, md desc
) as seqnum
from t
) t
where seqnum = 1;
答案 1 :(得分:2)
Sql server具有方便with ties
并允许Order by
中的row_number()。所以
select top 1 with ties t.*
from t
order by row_number()
over (partition by fc order by status asc, version desc, cd desc, md desc) ;
答案 2 :(得分:0)
使用GROUP BY子句:
SELECT FC,min(status),max(Version),max(CD),max(MD)
FROM YOUR_table
GROUP BY FC