如果嵌套案例的条件不同,则按分组

时间:2018-09-04 13:16:32

标签: sql sql-server-2000

我的问题与this问题有点相似,但有一个警告。在我的情况下,条件取决于不同的表,而不是一个表。给我带来麻烦的部分是GROUP BY部分。这是查询:

SELECT
    CASE 
        WHEN T1.ImportantColumn = 'Y'
        THEN 'Good'
        ELSE
            CASE
                WHEN T2.ImportantColumn = 1
                THEN 'Very Good'
                ELSE
                    CASE
                        WHEN T3.ImportantColumn IS NULL
                        THEN 'Bad'
                        ELSE T3.ImportantColumn
                    END
            END
    END AS WorkStatus,   
    SUM(case when T2.sex = 'M' THEN 1 ELSE 0 END) male , 
    SUM(case when T2.sex = 'F' THEN 1 ELSE 0 END) female , 
    COUNT(WorkStatus) AS [CountWorkStatus] 
FROM 
    Condition1Table T1 
    RIGHT JOIN Condition2Table T2 ON T1.city = T2.Code_id AND T1.field_name = 'cities' 
    INNER JOIN Condition3Table T3 ON T2.student_id = T3.student_id
GROUP BY T3.ImportantColumn, T2.ImportantColumn, T1.ImportantColumn -- <-- wrote this but I know it's wrong

这是IF ELSE场景。如果 Condition1Table.ImportantColumn 为'Y',则为'Good',否则,如果 Condition2Table.ImportantColumn 为1,则为'非常好',否则,如果 Condition3Table.ImportantColumn em>为NULL,然后为“坏”,否则为 Condition3Table.ImportantColumn 中的值。困难的部分是以期望的格式对数据进行分组,如下所示:

WorkStatus | male | female | CountWorkStatus
----------   -----  ------   ---------------
Good       |  3   |   7    | 10
Very Good  | 11   |   2    | 13
Bad        |  5   |   0    | 5
Val1       |  1   |   9    | 10
Val2       | 41   |   23   | 64

1 个答案:

答案 0 :(得分:0)

您似乎在问:“如何在不重复整个CASE语句的情况下对一个大型CASE语句进行分组?”

如果是这样,只需使用子查询即可。

然后CASE语句的结果具有您可以引用的列名。

这里的性能损失几乎为零,子查询扩展为类似于宏的查询。 SQL是一种声明性语言,它只是用于表达要解决的问题的语法。编译下来后,有一个程序要运行。因此,在考虑SQL时,您只需要语法即可表达您的问题。

SELECT
    WorkStatus,
    SUM(case when sex = 'M' THEN 1 ELSE 0 END) male , 
    SUM(case when sex = 'F' THEN 1 ELSE 0 END) female , 
    COUNT(WorkStatus) AS [CountWorkStatus] 
FROM
(
    SELECT
        CASE 
            WHEN T1.ImportantColumn = 'Y'
            THEN 'Good'
            ELSE
                CASE
                    WHEN T2.ImportantColumn = 1
                    THEN 'Very Good'
                    ELSE
                        CASE
                            WHEN T3.ImportantColumn IS NULL
                            THEN 'Bad'
                            ELSE T3.ImportantColumn
                        END
                END
        END AS WorkStatus,
        T2.sex
    FROM 
        Condition1Table T1 
        RIGHT JOIN Condition2Table T2 ON T1.city = T2.Code_id AND T1.field_name = 'cities' 
        INNER JOIN Condition3Table T3 ON T2.student_id = T3.student_id
)
  AS StatusBySex
GROUP BY
  WorkStatus