Sql distinct和group by boolean字段

时间:2016-10-21 10:32:01

标签: mysql sql

我想计算一些列的不同出现次数,并按两个布尔列

进行非分组
select count(Distinct some_column) as Uniques, sum(some_other_col)
from myTable T
where T.created_at>'2016-09-15'
group by T.col1, T.col2

此查询提供四个值

uniques when col1=true and col2=true
uniques when col1=true and col2=false
uniques when col1=false and col2=true
uniques when col1=false and col2=false

是否可以更改相同的查询并获取这三个值? 我无法获得结合前4个值的信息

uniques  (all)
uniques when col1=true 
uniques when col2=true

更新

实际上我想保留,因为还有一些其他值可以得到总和。

2 个答案:

答案 0 :(得分:2)

使用条件聚合:

select count(Distinct some_column) as Uniques,
       count(distinct case when t.col1 then some_column end) as Uniques_col1_true,
       count(distinct case when t.col2 then some_column end) as Uniques_col2_true
from myTable t
where t.created_at > '2016-09-15';

答案 1 :(得分:0)

试试这个

SELECT SUM(CASE WHEN col1 = TRUE
           AND col2 = TRUE THEN 1 ELSE 0 END) AS opt1,
       SUM(CASE WHEN col1 = TRUE
           AND col2 = FALSE THEN 1 ELSE 0 END) AS opt2,
FROM
    (SELECT DISTINCT col1,
                     col2,
                     somecolumn
     FROM TABLE T
     WHERE ...) AS TB