我正在尝试使用各种聚合函数生成摘要报告:MIN,MAX,SUM等。我遇到的问题是当我在使用case语句时尝试获取字段的MIN和MAX时。当我使用case语句时,我无法获得字段的MIN值。我可以用样本数据和sql语句来解释它:
字段:AccountNumber,Symbol,TradeDate,TransactionType,Price,Quantity,Amount 表:交易
AccountNumber, Symbol, TradeDate, TransactionType, Price, Quantity, Amount
123,"XYZ",1/2/2011,"Buy",15,100,1500
123,"XYZ",1/2/2011,"Buy",10,50,500
123,"XYZ",1/2/2011,"Sell",20,100,2000
456,"ABC",1/3/2011,"Buy",10,20,200
456,"ABC",1/3/2011,"Buy",15,30,450
789,"DEF",1/4/2011,"Sell",30,100,3000
查询:
SELECT AccountNumber,
Symbol,
SUM(case when TransactionType = "Buy" then 1 else 0) as TotalBuys,
SUM(case when TransactionType = "Sell" then 1 else 0) as TotalSells,
MIN(case when TransactionType = "Buy" then Price else 0) as MinBuy,
MAX(case when TransactionType = "Buy" then Price else 0) as MaxBuy,
MIN(case when TransactionType = "Sell" then Price else 0) as MinSell,
MAX(case when TransactionType = "Sell" then Price else 0) as MaxSell,
MIN(Price) as MinPrice,
MAX(Price) as MaxPrice
FROM Trades
Group By AccountNumber, Symbol
我期待的是以下结果:
AccountNumber, Symbol, TotalBuys, TotalSells, MinBuy, MaxBuy, MinSell, MaxSell, MinPrice, MaxPrice
123,"XYZ",2,1,10,15,20,20,10,20
456,"ABC",2,0,10,15,0,0,10,15
789,"DEF",0,1,0,0,30,30,30,30
但是,我得到以下结果:
AccountNumber, Symbol, TotalBuys, TotalSells, MinBuy, MaxBuy, MinSell, MaxSell, MinPrice, MaxPrice
123,"XYZ",2,1,**0**,15,**0**,20,**0**,20
456,"ABC",2,0,10,15,0,0,10,15
789,"DEF",0,1,0,0,30,30,30,30
当每个分组有两个不同的TransactionType时,Min字段(MinBuy,MinSell和MinPrice)将显示为0而不是预期。我在sql语句上做错了什么?还有另一种方法可以获得理想的结果吗?
答案 0 :(得分:16)
介于0和正数之间的最小值为0,您应该更改:
MIN(case when TransactionType = "Buy" then Price else 0)
通过
MIN(case when TransactionType = "Buy" then Price else Null)
Null不在聚合函数中计算。
多数人。
6年后编辑:
正如P5Coder所说,没有else
条款就足够了,我想在某些数据库品牌上end
是强制性的。这是:
MIN(case when TransactionType = "Buy" then Price end)