1

我正在寻找一种干净、简洁的方法来有条件地执行 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 操作的最佳方法是什么吗?

4

2 回答 2

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
于 2013-11-11T12:51:49.387 回答
0

我也打算建议与 相同CASE@Matt suggested但我想您可能想要全部的总数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
于 2013-11-11T12:56:58.417 回答