具有聚合功能和CASE-WHEN语句的T-SQL查询

时间:2018-06-22 08:02:59

标签: tsql select group-by aggregation case-when

我有一个简单但非常重要的概念需要在T-SQL中清除。

我正在针对一个表编写许多T-SQL查询,其中包含许多聚合和GROUP BY。

现在,在我的T-SQL查询的SELECT子句中,我有一个CASE-WHEN语句。请看下面:

声明1:

SELECT X, Y, Z, 

A = CASE
        WHEN P = 1 THEN B
        ELSE Q
    END,

SUM(Sales)

FROM mytable

GROUP BY  
X, Y, Z,
CASE
     WHEN P = 1 THEN B
     ELSE Q
END

现在语句1可以写为语句2吗?

声明2:

SELECT X, Y, Z, 

A = CASE
        WHEN P = 1 THEN B
        ELSE Q
    END,

SUM(Sales)

FROM mytable

GROUP BY  
X, Y, Z,
P, B, Q

陈述1是否等于陈述2?

SELECT子句中的CASE-WHEN是否可以在GROUP BY子句中修改为单独的列?

结果集将始终相同吗?

1 个答案:

答案 0 :(得分:0)

差异取决于您可能从P语句的结果中从BQCASE列中获得的不同值的数量。您可以在此示例中找到不同之处。

IF OBJECT_ID('tempdb..#Data') IS NOT NULL
    DROP TABLE #Data

CREATE TABLE #Data (
    P INT,
    B INT,
    Q INT,
    Sales INT)

INSERT INTO #Data (
    P,
    B,
    Q,
    Sales)
VALUES
    (1, 20, 300, 1000),
    (1, 20, 400, 500),
    (2, 1, 1, 50),
    (2, 1, 1, 250)


-- Statement 2
SELECT
    P,
    B,
    Q,
    TotalSales = SUM(D.Sales)
FROM
    #Data AS D
GROUP BY
    P,
    B,
    Q

/*
    All different combinations of PBQ and listed, and their sales added

    P   B   Q   TotalSales
    1   20  300 1000
    1   20  400 500
    2   1   1   300
*/



-- Statement 1
SELECT
    CaseResult = CASE WHEN P = 1 THEN B ELSE Q END,
    TotalSales = SUM(D.Sales)
FROM
    #Data AS D
GROUP BY
    CASE WHEN P = 1 THEN B ELSE Q END

/*

    The grouping value depends on value B when P = 1 (and not on Q!) so 
    all records with P = 1 and same B are grouped together and
    all records with P = 0 and same Q are grouped together

    CaseResult  TotalSales
    1           300
    20          1500
*/

在某些情况下,从CASEPBQ的组合,数据不会生成不同的值,在这种情况下,两个查询的结果将相同。