汇总postgres联盟结果

时间:2016-04-04 12:35:34

标签: sql postgresql

我试图在SQL中使用postgres数据库中的单个表获得每个日期的singel结果行。我尝试使用Union,但我认为这不是正确的方法。可以帮助我构建正确的SQL。

表格内容的示例数据列:id,creationdate,contenttype

1 |2016-04-02|PAGE
2 |2016-04-02|ATTACHMENT
3 |2016-04-02|PAGE
4 |2016-04-03|ATTACHMENT
5 |2016-04-03|PAGE
6 |2016-04-03|ATTACHMENT
7 |2016-04-03|PAGE
8 |2016-04-04|ATTACHMENT
9 |2016-04-04|ATTACHMENT
10|2016-04-04|ATTACHMENT

如果使用此SQL查询:

SELECT 
  date(creationdate) AS create_date,
  COUNT(*) AS PAGE,0 AS ATTACHMENT 
FROM 
  content 
WHERE 
  contenttype='PAGE' GROUP BY content.creationdate 
UNION
SELECT 
  date(creationdate) AS create_date,
  0 AS PAGE,COUNT(*) AS ATTACHMENT
FROM 
  content 
WHERE 
  contenttype='ATTACHMENT' GROUP BY content.creationdate 
ORDER BY create_date ASC;

我得到了结果

|create_date|PAGE|ATTACHMENT|
|2016-04-02|0|2|
|2016-04-02|1|0|
|2016-04-03|0|2|
|2016-04-03|1|0|
|2016-04-04|3|0|

我想要的是:

|create_date|PAGE|ATTACHMENT|
|2016-04-02|1|2|
|2016-04-03|2|2|
|2016-04-04|3|0|

3 个答案:

答案 0 :(得分:1)

您需要条件聚合

SELECT 
  date(creationdate) AS create_date,
  SUM(CASE WHEN contenttype='PAGE' THEN 1 ELSE 0 END) AS PAGE,
  SUM(CASE WHEN contenttype='ATTACHMENT' THEN 1 ELSE 0 END) AS ATTACHMENT
FROM 
  content 
GROUP BY content.creationdate 
ORDER BY create_date ASC;

答案 1 :(得分:1)

您可以通过仅从表中选择一次来进行条件聚合:

SELECT date(creationdate) AS create_date,
       count(CASE WHEN contenttype='PAGE' then 1 end) as PAGE,
       count(CASE WHEN contenttype='ATTACHMENT' then 1 end) as ATTACHMENT
FROM 
  content 
GROUP BY content.creationdate 
ORDER BY create_date ASC;

答案 2 :(得分:0)

有几种方式:

SELECT   date(c.creationdate) AS create_date,
p p_count,a_count 
FROM 
(SELECT DISTINCT creationdate FROM content) c INNER JOIN (SELECT  creationdate,count() p_count FROM CONTENT GROUP
BY creationdate,contenttype   HAVING contenttype='PAGE') p on p.creationdate=c.creationdate
INNER JOIN (SELECT  creationdate,count() a_count FROM CONTENT GROUP
BY creationdate,contenttype   HAVING contenttype='ATTACHMENT') p
ON p.creationdate=c.creationdate ORDER BY c.creationdate

一个是这个