SQL Query根据某些条件选择一行

时间:2017-02-27 12:41:48

标签: sql sql-server

在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

3 个答案:

答案 0 :(得分:8)

是。使用TOPORDER 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