T-SQL条件SUM操作

时间:2013-11-11 12:45:42

标签: sql sql-server

我正在寻找一种干净,简洁的方式来有条件地执行SUM操作。我知道这要相当直接,但我不确定如何继续。为了表明我的意思,请看一下......

    DECLARE @Test TABLE
(
    LevelID int,
    DataFieldID INT,
    RangeID INT,
    Value FLOAT
)

INSERT INTO @Test VALUES (22, 6, 117, 100)
INSERT INTO @Test VALUES (22, 6, 122, 100)
INSERT INTO @Test VALUES (22, 6, 126, 100)

INSERT INTO @Test VALUES (22, 7, 117, 100)
INSERT INTO @Test VALUES (22, 7, 122, 100)
INSERT INTO @Test VALUES (22, 7, 126, 100)

INSERT INTO @Test VALUES (23, 6, 117, 100)
INSERT INTO @Test VALUES (23, 6, 122, 100)
INSERT INTO @Test VALUES (23, 6, 126, 100)

INSERT INTO @Test VALUES (23, 7, 117, 100)
INSERT INTO @Test VALUES (23, 7, 122, 100)
INSERT INTO @Test VALUES (23, 7, 126, 100)


SELECT
    LevelID, 
    RangeID, 
    SUM(Value[where DataFieldID = 6]) / SUM(Value[where DataFieldID = 7])
FROM
    @Test
GROUP BY LevelID, RangeID

知道实现上述SUM操作的最佳方法是什么?

2 个答案:

答案 0 :(得分:5)

您可以在聚合中使用CASE WHEN

SELECT
    LevelID, 
    RangeID, 
    SUM(CASE WHEN DataFieldID = 6 THEN Value ELSE 0 END) / 
    SUM(CASE WHEN DataFieldID = 7 THEN Value ELSE 0 END)
FROM
    @Test
GROUP BY LevelID, RangeID

答案 1 :(得分:0)

我还建议使用与@Matt suggested相同的CASE,但我想你可能想要所有DataFieldId的总数,如......?也许我误解了,如果是这样的话,我会删除......

SELECT  LevelID ,
        RangeID ,
        a.total
FROM    @Test
        INNER JOIN ( SELECT SUM(Value) total ,
                            DataFieldID
                     FROM   @Test
                     GROUP BY DataFieldID
                   ) a ON [@Test].DataFieldID = a.DataFieldID
GROUP BY LevelID ,
        RangeID ,
        a.total