使用Case语句时MIN和MAX的问题

问题描述 投票:2回答:1

我正在尝试使用各种聚合函数生成摘要报告: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语句上做错了什么?有没有其他方法可以获得理想的结果?

sql
1个回答
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)
© www.soinside.com 2019 - 2024. All rights reserved.