如何在参数中传递聚合类型?

时间:2017-09-05 17:39:02

标签: sql tsql

我想创建一个存储过程,我收到(不知何故,可以是varchar或其他有效的东西)聚合函数(SUM,MIN,MAX,STD等)。

CREATE PROCEDURE test
    @aggregType varchar(5)
AS BEGIN
    SELECT @aggregType(column1) as column1Aggregated,
           timestamp_local
    FROM test_table
    GROUP BY timestamp_local
    ORDER BY timestamp_local
END
GO

显然这不起作用。我怎样才能使它工作?在文献中找不到任何这方面的例子。

谢谢!

1 个答案:

答案 0 :(得分:2)

即使这看起来有限,HABO的消化也会是这样的:

CREATE PROCEDURE test
    @aggregType varchar(5)
AS BEGIN
    SELECT CASE @aggregType 
            WHEN 'SUM' THEN SUM(column1)
            WHEN 'MIN' THEN MIN(column1) 
            WHEN 'MAX' THEN MAX(column1) 
            WHEN 'AVG' THEN AVG(column1) 
                END as column1Aggregated,
           timestamp_local
    FROM test_table
    GROUP BY timestamp_local
    ORDER BY timestamp_local
END
GO

这绝不是动态