SQL Select Distinct基于条件

时间:2016-12-27 16:30:34

标签: sql sql-server

假设: STAGINGLINE中的项目状态:0 - 未开始,1 - 已验证,2 - MISCOUNT

每个ASN只需显示一行,因此最简单的方法是使用DISTINCT ....

SELECT DISTINCT ASN, STATUS 
FROM STAGINGLINE

但是,由于多种STATUS可能性,我不能使用简单的不同,你会得到每个状态的倍数。

结果集应仅显示2个“ASN”:123和343

示例STAGINGLINE表

案例1:

(ASN #, ITEM #, STATUS, QTY ,ACTUAL)
123   898      0       4      NULL
123   344      0       9      NULL
123   123      0       2      NULL
123   534      0       1      NULL
343   111      1       6      6

ResultSet需要是:

123  NOT STARTED (because all 0)
343  VERIFIED

案例2:

(ASN #, ITEM #, STATUS, QTY ,ACTUAL)
123   898      1       4      4
123   344      0       9      NULL
123   123      0       2      NULL
123   534      0       1      NULL

ResultSet需要是:

123  IN PROGRESS (because at least one of them is not in a 0 STATUS)
343  VERIFIED

案例3:

(ASN #, ITEM #, STATUS, QTY ,ACTUAL)
123   898      1       4      4
123   344      2       9      5  <- MISCOUNT
123   123      0       2      NULL
123   534      0       1      NULL

ResultSet需要是:

123  MISCOUNT (because of the existence of a 2 in at least one of the STATUS column)
343  VERIFIED

案例4:

(ASN #, ITEM #, STATUS, QTY ,ACTUAL)
123   898      1       4      4
123   344      1       9      9
123   123      1       2      2
123   534      1       1      1

ResultSet需要是:

123  VERIFIED (because all are STATUS of 1)
343  VERIFIED

2 个答案:

答案 0 :(得分:3)

您在寻找libmyshare.so

max()

或者select asn, max(status) from t group by asn; max()

case

编辑:

规则似乎更详细一些:

select (case max(status) when 0 then 'NOT STARTED'
                         when 1 then 'VERIFIED'
                         when 2 then 'MISCOUNT'
        end)
from t
group by asn;

答案 1 :(得分:2)

你能试试吗,

SELECT ASN, 
        CASE WHEN MAX_STATUS = 2 THEN 'MISCOUNT'
             WHEN MAX_STATUS = 0 THEN 'NOT STARTED'
             WHEN MAX_STATUS = 1 AND MIN_STATUS = 1 THEN 'VERIFIED'
             WHEN MAX_STATUS = 1 AND MIN_STATUS = 0 THEN 'IN-PROGRESS'
         END STATUS
FROM         
(SELECT ASN, MAX(STATUS) MAX_STATUS, MIN(STATS) MIN_STATUS
FROM STAGELINE
GROUP BY ASN) A