2017-03-14 106 views
0

我有一個訂單表,我想要顯示一個報告,顯示從單個表中拒絕的月份,總訂單和總訂單。在單個查詢中顯示2個計數結果

表有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 
+1

哪些DBMS您使用的? Postgres的?甲骨文? –

回答

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) 
1

這可能取決於你所使用的數據庫管理系統,但最應該支持這樣的事情:

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) 
+0

很好用,謝謝,還有一個想法是在下一欄中顯示REJECTS佔TotalOrders百分比的最佳方式是什麼? –

+0

這絕對取決於數據庫管理系統,但你可以從'count(當supplierRejected = 1然後rptID結束時)* 100/count(rtpID')開始。有些數據庫可能會讓您按名稱引用以前的列,而不是重新輸入表達式來計算它們(或者,您可能通過將查詢包裝爲子查詢來獲得相同的效果) –

相關問題