2016-11-23 46 views
0

一個人爲的例子:說我有一個簡單的表格,有2列 - 日期和(數字)ID。我想知道,每一天,甚至有多少比例的ID。在SQL查詢中,我可以對不同的結果列使用不同的where子句嗎?

我可以在2個查詢做到這一點:

查詢#1:

select date, id % 2, count(*) 
from my_table 
group by date, id % 2 
order by date, id % 2 

查詢#2:

select date, count(*) 
from my_table 
group by date 
order by date 

然後我手動(即,在電子表格)排隊列和做數學。

這當然很麻煩 - 有沒有辦法在一個查詢中做到這一點?

喜歡的東西:

select 
    date, 
    [count where id % 2 = 0], [total count], 
    [count where id % 2 = 0/total count] 
from my_table 
group by date 
order by date 
+1

您正在使用哪個數據庫管理系統?另外:[編輯]你的問題,並添加一些樣本數據和基於該數據的預期輸出。 [_Formatted_](http://dba.stackexchange.com/help/formatting)**文本**請[無屏幕截圖](http://meta.stackoverflow.com/questions/285551/why-may-i - 未上傳圖像-的代碼上那麼當灰化-A-問題/ 285557#285557) –

回答

2

使用條件sum()

select date, 
     sum(case when id % 2 = 0 then 1 else 0 end) * 100/count(*) as evenPercentage, 
     sum(case when id % 2 = 1 then 1 else 0 end) * 100/count(*) as unevenPercentage, 
     count(*) as totalCount, 
     sum(case when id % 2 = 0 then 1 else 0 end) as evenCount, 
     sum(case when id % 2 = 1 then 1 else 0 end) as unevenCount 
from my_table 
group by date 
order by date 
相關問題