1

I'm looking for a clean, concise way to perform a SUM operation conditionally. I know this gotta be fairly straight-forward but I'm unsure of how to proceed. To demonstare what I mean, take a look at this...

    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

Any idea what would be the best way to achieve the above SUM operation?

2 Answers 2

5

You can use CASE WHEN within the aggregate:

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
Sign up to request clarification or add additional context in comments.

Comments

0

I was also going to suggest the same CASE as @Matt suggested, but I figured you might want the total across all DataFieldId, as in...? maybe I've misunderstood, I will delete if that's the case...

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

2 Comments

I know there's only two answers at the moment, but you should avoid using positional language to refer to answers on stack overflow - in (30 seconds/a day/a week/a year), the answer that is "above" may no longer be the answer you were attempting to refer to, due to voting, deletions, etc. It's better to include a link to the answer you want to refer to (use the share option at the bottom to get a link) (I usually also put the name of the author of the answer)
@Damien_The_Unbeliever, thanks for the tip, I have updated the post. Although, I will probably delete the post soon as my interpretation looks incorrect...I'll wait for the OP to confirm though.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.