SQL Server中的CASE表达式

时间:2018-08-29 19:10:22

标签: sql sql-server

我有三个表,下面有一些记录。我期望在组字段中返回两个不同的键,并带有“ BERRY”。但是,例如KEYs = 179526189显示的是BERRY和COCA,而不仅仅是BERRY。

表A

AGE AGE_IND     KEYS
34  (null)      179526189
6   N           179526390

Table B
ID          STATUS      FK_KEY
16478           (null)  179526189
16478           (null)  179526390
16479           (null)  179526189
16479           (null)  179526390

表C

FK_ID   PRO_CODE    DEL_DT
16478   Drug        6/10/2014 12:00:00 AM
16479   Drug        (null)  



SELECT KEYS,
CASE WHEN (AGE < 18 AND AGE_IND = 'Y') AND (B.STATUS != 'S' or B.STATUS is null) THEN 'APPLE'
WHEN C.PRO_CODE = 'Drug' THEN 'BERRY'
WHEN AGE >= 18 THEN 'COCA'
ELSE 'APPLE' END as Groups,
COUNT(DISTINCT KEYS) AS CT
FROM #tableA A 
LEFT OUTER JOIN #tableB B
ON (A.KEYS = B.FK_KEY AND (B.STATUS <>'S' or B.STATUS IS NULL))
LEFT OUTER JOIN #tableC C
ON (B.ID = C.FK_ID AND C.DEL_DT IS NULL)
GROUP BY KEYS,
CASE WHEN (AGE < 18 AND AGE_IND = 'Y') AND (B.STATUS != 'S' or B.STATUS is null) THEN 'APPLE'
WHEN C.PRO_CODE = 'Drug' THEN 'BERRY'
WHEN AGE >= 18 THEN 'COCA'
ELSE 'APPLE' END

运行上面的查询,产生

KEYS        Groups  CT
179526189   BERRY   1
179526189   COCA    1
179526390   APPLE   1
179526390   BERRY   1

请您告诉我我的CASE表达式有什么问题吗?这样我的预期结果就会产生:

KEYS        Groups  CT
179526189   BERRY   1
179526390   BERRY   1

谢谢 乔

1 个答案:

答案 0 :(得分:1)

您正在按GROUPS分组,因此每一个都可以得到。选一个!目前尚不清楚您如何选择'BERRY',但是如果您想每KEYS排一行,则想法是仅将其包括在GROUP BY中:

SELECT KEYS,
       MAX(CASE WHEN (AGE < 18 AND AGE_IND = 'Y') AND (B.STATUS != 'S' or B.STATUS is null) THEN 'APPLE'
                WHEN C.PRO_CODE = 'FMU' THEN 'BERRY'
                WHEN AGE >= 18 THEN 'COCA'
                ELSE 'APPLE'
           END) as Groups,
          COUNT(DISTINCT KEYS) AS CT
FROM #tableA A LEFT OUTER JOIN
     #tableB B
     ON A.KEYS = B.FK_KEY AND (B.STATUS <>'S' or B.STATUS IS NULL) LEFT OUTER JOIN 
     #tableC C
     ON B.ID = C.FK_ID AND C.DEL_DT IS NULL
GROUP BY KEYS;