Skip to content
Advertisement

How do I display two different sums of the same price with different parameters?

I need to get the SUM of 2 different Totals. One is just the Total and the second one is the Total that only includes products that are sold for less than $25.

SELECT SUM(Price) AS Total
FROM Sales (NOLOCK)

SELECT SUM(Price) AS TotalUnder
FROM Sales (NOLOCK)
WHERE Price < 25

Expected Outcome should look like this

|Total | TotalUnder |

| 20000 | 1500 |

Advertisement

Answer

Use conditional aggregation:

SELECT SUM(Price) AS Total,
       SUM(CASE WHEN Price < 25 THEN Price ELSE 0 END) as TotalUnder
FROM Sales ;

Notice that I removed the NOLOCK hint. This tends to be over-used and is generally not necessary. Only use it if you really understand how SQL Server implements locking and you know what NOLOCK is doing.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement