计数区别于答案并排而不是在下面

时间:2016-05-03 19:26:33

标签: postgresql count distinct

这是我的问题:

SELECT substring(date,1,10), count(distinct id),
CASE WHEN name IS NOT NULL THEN 1 ELSE 0 END
FROM table
WHERE (date >= '2015-09-01')
GROUP BY substring(date,1,10), CASE WHEN name IS NOT NULL THEN 1 ELSE 0 END
ORDER BY substring(date,1,10)

这是我的结果:

substring     count     case
2015-09-01     20472      0
2015-09-01         7      1
2015-09-02     20465      0
2015-09-02       470      1

我希望它看起来像这样:

substring     count    count
2015-09-01    20472        7
2015-09-02    20465      470

谢谢!

3 个答案:

答案 0 :(得分:1)

使用PostgreSQL 9.4或更高版本,我们可以使用新的FILTER子句直接过滤聚合:

SELECT substring(date,1,10),
  count(distinct id),
  count(*) FILTER (WHERE name IS NOT NULL)
FROM table
WHERE (date >= '2015-09-01')
GROUP BY 1
ORDER BY 1

答案 1 :(得分:0)

使用count in count来获取某些条件的列(名称IS NOT NULL),如下所示:

SELECT substring(date,1,10)
, count(distinct CASE WHEN name IS NOT NULL THEN id ELSE null END ) AS count1
, count(distinct CASE WHEN name IS NOT NULL THEN null ELSE id END ) AS count2
FROM table
WHERE (date >= '2015-09-01')
GROUP BY substring(date,1,10)
ORDER BY substring(date,1,10)

您还可以使用子查询来创建列:

SELECT dt, Count(id1) count1, Count(distinct id2) count2
FROM (    
  SELECT distinct substring(date,1,10) AS dt
  , CASE WHEN name IS NOT NULL THEN id ELSE null END AS id1
  , CASE WHEN name IS NOT NULL THEN null ELSE id END AS id2,
  FROM table
  WHERE (date >= '2015-09-01')) d
GROUP BY dt
ORDER BY dt

答案 2 :(得分:0)

SELECT substring(date,1,10)
, count(distinct CASE WHEN name IS NOT NULL THEN id ELSE null END ) AS count1
, count(distinct CASE WHEN name IS NOT NULL THEN null ELSE id END ) AS count2
FROM event
WHERE (date >= '2015-09-01')
GROUP BY substring(date,1,10)
ORDER BY substring(date,1,10)

这给了我一个这样的答案:(这正是我想要的,所以非常感谢你)

substring    count1   count2
2015-09-01        7    20472
2015-09-02      470    20465