2016-11-23 11 views
0

例:私は、日付と(数値)IDの2つの列を持つ単純なテーブルを持っているとします。私は毎日、何パーセントの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 

そして、私は手動で(つまり、スプレッドシート内の)ラインアップ列と計算を行う。

これはもちろん面倒です - これを1つのクエリで行う方法はありますか?

ような何か:

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) -not-upload-images-of-code-on-so-ask-a-question/285557#285557) –

答えて

2

は、DBMSは、使用している条件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 
関連する問題