事务 SQL、GROUP BY 使用 Case 和聚合函数

问题描述 投票:0回答:1

我正在尝试使用变量/参数以及“CASE”语句来确定要使用的“Group By”子句。

我收到以下错误:

消息 8120,第 16 层,状态 1,第 77 行 列“Field_1”在选择列表中无效,因为它不包含在任一列表中 聚合函数或 GROUP BY 子句。

我使用的示例 SQL 如下:

DECLARE @OrderBy nvarchar(15) = 'Date';
DECLARE @StartDate date = '01/01/2023';
DECLARE @EndDate date = '12/31/2023';

SELECT Field_1, Field_2, Field_3, SUM(Field_4) AS 'Sum'
FROM Table_1
WHERE
    Field_2 IN ('A', 'B', 'C', 'D', 'E')
    AND 
    Field_3 > 1
    AND
    Field_3 < 20
    AND
    Field_1 >= @StartDate
    AND
    Field_1 <= @EndDate

/*
    If @OrderBy = 'Date' 
        THEN "GROUP BY" should be
            GROUP BY Field_1, Field_2, Field_3
    IF @OrderBy = 'Location'
        THEN "GROUP BY" should be
            GROUP BY Field_3, Field_2, Field_1
*/
GROUP BY
    CASE WHEN @OrderBy = 'Date' 
        THEN [Field_1]
    END, 
    CASE WHEN @OrderBy = 'Date' 
        THEN [Field_2]
    END,
    CASE WHEN @OrderBy = 'Date' 
        THEN [Field_3]
    END,
    
    CASE WHEN @OrderBy = 'Location' 
        THEN [Field_2]
    END, 
    CASE WHEN @OrderBy = 'Location' 
        THEN [Field_3]
    END,
    CASE WHEN @OrderBy = 'Location' 
        THEN [Field_1]
    END

/*
    If @OrderBy = 'Date' 
        THEN "GROUP BY" should be
            ORDER BY Field_1, Field_2, Field_3
    IF @OrderBy = 'Location'
        THEN "ORDER BY" should be
            ORDER BY Field_3, Field_2, Field_1
*/
ORDER BY
    CASE WHEN @OrderBy = 'Date' 
        THEN [Field_1] 
    END,
    CASE WHEN @OrderBy = 'Date'
        THEN [Field_2]
    END,        
    CASE WHEN @OrderBy = 'Date'
        THEN [Field_3] 
    END,

    CASE WHEN @OrderBy = 'Location' 
        THEN [Field_2]
    END,        
    CASE WHEN @OrderBy = 'Location'
        THEN [Field_3]
    END,        
    CASE WHEN @OrderBy = 'Location'
        THEN [Field_1]
    END

目标是能够使用输入参数来确定正确的“分组依据”,以便我可以使用单个存储过程来处理任何情况,而不必拥有多个存储过程。

有人知道如何进行这项工作吗?

谢谢,

埃里克

sql group-by parameters case
1个回答
0
投票

GROUP BY 中的列顺序并不重要。您只需要 ORDER BY 中的列的条件顺序

SELECT Field_1, Field_2, Field_3, SUM(Field_4) AS 'Sum'
FROM Table_1
WHERE
    Field_2 IN ('A', 'B', 'C', 'D', 'E')
    AND 
    Field_3 > 1
    AND
    Field_3 < 20
    AND
    Field_1 >= @StartDate
    AND
    Field_1 <= @EndDate
GROUP BY
    [Field_1],[Field_2], [Field_3]
ORDER BY
    CASE @OrderBy 
      WHEN 'Date' THEN [Field_1] 
      WHEN 'Location' THEN [Field_2]
    END,
    CASE @OrderBy 
      WHEN 'Date' THEN [Field_2] 
      WHEN 'Location' THEN [Field_3]
    END,
    CASE @OrderBy 
      WHEN 'Date' THEN [Field_2] 
      WHEN 'Location' THEN [Field_1]
    END
© www.soinside.com 2019 - 2024. All rights reserved.