[英]How to select two SUMs from one table but one SUM must be made from only max. data
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. 我需要获得房间2,4的SUM(论文),我知道如何获得(它将在一起100)但是我还需要获得此查询SUM(笔)也适用于房间2,4但仅为了最高价值每个房间。 It will be for Room 2 value 45 and for Room 4 value 25 in this table and SUM must be 70.
它将用于房间2值45和此表中房间4值25,并且SUM必须为70。
I have used this code but ofcourse it is not working correct for Pens value... 我已经使用过这段代码,但是当然它对Pens值不正确...
SELECT SUM(Papers) AS Papers, SUM(DISTINCT Pens) AS Pens FROM MyTable
WHERE (Room = '2' OR Room = '4')
THX for help THX寻求帮助
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')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.