在SQL查询中,我可以为不同的结果列使用不同的where子句吗?

时间:2016-11-23 19:26:55

标签: sql

一个人为的例子:说我有一个包含2列的简单表 - 日期和(数字)id。我想知道,每天都有多少百分比的ID。

我可以在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 个答案:

答案 0 :(得分: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