【问题标题】:group by in case of nested cases with conditions on different tables在嵌套情况下分组,条件在不同表上
【发布时间】:2019-02-09 13:03:23
【问题描述】:

我的问题与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”则“好”,否则如果 Condition2Table.ImportantColumn 为 1 则“非常好”,否则如果 Condition3Table.ImportantColumn em> 为 NULL,然后是 'bad',否则为 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

【问题讨论】:

  • 不需要嵌套。只需将不同的 WHEN 放在同一个 case 表达式中即可。

标签: sql sql-server-2000


【解决方案1】:

您似乎在问“如何在不重复整个 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-10-10
    • 2017-09-03
    • 1970-01-01
    • 2020-10-18
    • 1970-01-01
    • 2021-07-04
    • 1970-01-01
    相关资源
    最近更新 更多