SQL:将案例表达式中的值用于下一列

时间:2018-07-16 23:06:42

标签: sql sql-server

尝试考虑一种更有效的方式来编写我的查询。我有一条很长的陈述,用于汇总会计总帐,我的目标是在三列中进行汇总。

Select 
    Month, Sum(Value1), Sum (Budget),
    Case 
       When Field1 In (1001, 1002, 1003, 1004) Then 'Hardware Expense'
       When Field1 In (2001, 2002, 2003, 2004) Then 'Software Expense'
       When Field1 In (3001, 3002, 3003, 3004) Then 'Product Sales' 
    End As "Aggregation1",
    Case 
       When Field1 In (1001, 1002, 1003, 1004, 2001, 2002, 2003) Then 'Expenses'
       When Field1 In (3001, 3002, 3003, 3004) Then 'Sales' End As "Aggregation2"

虽然可行,但我的实际陈述要长得多。理想情况下,我将“硬件支出”和“软件支出”称为变量。

When Aggregation1 In ('Hardware Expense', 'Software Expense') then 'Expenses'

最终输出为

Month, Sum(Value1), Sum (Budget), Aggregation1, Aggregation2, Aggregation3

感谢您的光临! -马克

1 个答案:

答案 0 :(得分:1)

查找表可以在这里提供帮助,但您可以按原样使用CROSS APPLY运算符动态创建命名列,您可以在同一查询中引用它们。

请注意,稍后在查询中如何使用新定义的Aggregation1列。

SELECT
    Month, Sum(Value1), Sum (Budget),
    A1.Aggregation1,
    A2.Aggregation2
FROM
    SomeTable
    CROSS APPLY
    (
        SELECT
            CASE
                WHEN Field1 In (1001, 1002, 1003, 1004) Then 'Hardware Expense'
                WHEN Field1 In (2001, 2002, 2003, 2004) Then 'Software Expense'
                WHEN Field1 In (3001, 3002, 3003, 3004) Then 'Product Sales' 
            END AS Aggregation1
    ) AS A1
    CROSS APPLY
    (
        SELECT
            CASE
                WHEN Aggregation1 In ('Hardware Expense', 'Software Expense') then 'Expenses'
                WHEN Aggregation1 In ('Product Sales') then 'Sales'
            END AS Aggregation2
    ) AS A2
;