我有一个订单表,我想显示一个报告,显示从单个表中拒绝的月份,总订单和总订单。
该表有我想要使用的dtcomplete,rtpID和supplierReject,这几乎让我在那里但是1月份应该只有1个拒绝显示,我希望子查询只检查分组的月份
select datename(month, dtComplete) as Month, count(rtpID) as TotalOrders,
(select count(*) from RTPMaindetails where SupplierRejected = 1 and datename(month, dtComplete) = datename(month, RTPMaindetails.dtComplete) group by datepart(month,dtcomplete) ) as Rejects
from RTPMaindetails
where datepart(year,dtComplete) = 2017
group by datepart(month,dtcomplete),datename(month, dtComplete)
order by datepart(month,dtcomplete)
节目:
Month TotalOrders Rejects
January 515 1
February 308 1
March 156 1
应该显示
Month TotalOrders Rejects
January 515 1
February 308 0
March 156 0
答案 0 :(得分:1)
这可能取决于您使用的DBMS,但大多数应该支持这样的内容:
select datename(month, dtComplete) as Month
, count(rtpID) as TotalOrders,
, count(case when SupplierRejected = 1 then rtpID end) as Rejects
from RTPMaindetails
where datepart(year,dtComplete) = 2017
group by datepart(month,dtcomplete),datename(month, dtComplete)
order by datepart(month,dtcomplete)
答案 1 :(得分:0)
您可以使用单个查询
select
datename(month, dtComplete) as Month
, count(rtpID) as TotalOrders
, sum( case when SupplierRejected = 1 then 1 else 0 ) as Rejects
from RTPMaindetails
where datepart(year,dtComplete) = 2017
group by datepart(month,dtcomplete)
order by datepart(month,dtcomplete)