I have this table
Room Papers Pens
1 30 30
3 10 10
4 15 15
4 35 25
3 25 5
2 15 45
2 5 15
4 7 8
4 11 9
4 12 11
1 8 8
I need to get SUM(Papers) for Rooms 2,4 which I know how to get (it will be together 100) but then I need also get in this query SUM(Pens) also for Rooms 2,4 BUT only for highest value for each Room. It will be for Room 2 value 45 and for Room 4 value 25 in this table and SUM must be 70.
I have used this code but ofcourse it is not working correct for Pens value...
SELECT SUM(Papers) AS Papers, SUM(DISTINCT Pens) AS Pens FROM MyTable
WHERE (Room = '2' OR Room = '4')
THX for help
You can do it with conditional aggregation:
SELECT
SUM(Papers) AS Papers,
SUM(
CASE
WHEN EXISTS (
SELECT 1 FROM MyTable
WHERE Room = m.Room AND Pens > m.Pens
) THEN 0
ELSE Pens
END
) AS Pens
FROM MyTable m
WHERE (Room = '2' OR Room = '4')
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.