SQL Server中带子查询的CASE语句

时间:2018-04-03 16:14:24

标签: sql sql-server group-by subquery case

请查看我的SQL查询。

select 
CASE 
    WHEN (SELECT COUNT(COL1) FROM FACT_ACTIVITY group BY FACT_ACTIVITY.COL2)>1
            THEN (SELECT COUNT(COL3) FROM FACT_ACTIVITY) 
    WHEN (SELECT COUNT(COL1) FROM FACT_ACTIVITY group BY FACT_ACTIVITY.COL2)=1
            THEN (SELECT COUNT(COL4) FROM FACT_ACTTIVITY)
            END
,EXTRACT(year from fa.INC_START_DATETIME) AS YearOFF
,COUNT(fa.COL2) AS OffCount from FACT_ACTIVITY fa INNER JOIN
DIM_OFF_TYPE do ON fa.OFF_TYPE_ID = do.OFF_TYPE_ID
WHERE fa.OFF_TYPE_ID IN (24001) and YEAR(fa.INC_START_DATETIME) IN (2016,2017)
group by do.OFF_TYPE_DESCR,YEAR(fa.INC_START_DATETIME)

WHEN情况下的子查询给出了很多行,但我希望子查询检查每个FACT_ACTIVITY_ID并查看count(col2)> 1并执行THEN语句。

1 个答案:

答案 0 :(得分:0)

要使子查询为每个FACT_ACTIVITY_ID返回一行,您必须将该过滤器放在WHERE子句中:

SELECT 
            CASE 
                WHEN (SELECT    COUNT(COL1) 
                      FROM      FACT_ACTIVITY fa2 
                      WHERE     fa2.FACT_ACTIVITY_ID = fa.FACT_ACTIVITY_ID 
                      GROUP BY  FACT_ACTIVITY.COL2) > 1
                    THEN (SELECT COUNT(COL3) FROM FACT_ACTIVITY) 

                WHEN (SELECT    COUNT(COL1) 
                      FROM      FACT_ACTIVITY fa2 WHERE fa2.FACT_ACTIVITY_ID = fa.FACT_ACTIVITY_ID
                      GROUP BY  FACT_ACTIVITY.COL2)=1
                        THEN (SELECT COUNT(COL4) FROM FACT_ACTTIVITY)
                END AS GiveMeAnAlias
            ,EXTRACT(year from fa.INC_START_DATETIME) AS YearOFF
            ,COUNT(fa.COL2) AS OffCount 
FROM        FACT_ACTIVITY fa 
            INNER JOIN DIM_OFF_TYPE do ON fa.OFF_TYPE_ID = do.OFF_TYPE_ID
WHERE       fa.OFF_TYPE_ID IN (24001) 
                AND YEAR(fa.INC_START_DATETIME) IN (2016,2017)
GROUP BY    do.OFF_TYPE_DESCR,
            YEAR(fa.INC_START_DATETIME)

注意表FACT_ACTIVITY" fa2"的表别名在子查询中区分子查询中的FACT_ACTIVITY与外部主查询中的FACT_ACTIVITY。

还要注意可读性和可维护性以及良好的空白区域和标签:)