在Postgresql中共享日期计算两个表

时间:2015-10-07 04:31:31

标签: sql postgresql

我有两个单独的客户表A和B.我正在尝试按日期统计在同一查询中在A和B中创建的客户。我可以使用Union All获取正确的数据,但没有正确分组。

我想要这样的数据:

date,count A created, count B created
4/15/2015,1,5

而不是:

date, count
4/15/2015, 1
4/15/2015, 5

感谢帮助!

2 个答案:

答案 0 :(得分:0)

只要使用cte,如果你每天都没有约会,就必须小心。在这种情况下,您需要一个日期表,在没有销售时获得0。

另请尽量不要使用date之类的保留字作为字段名

with countA as (
     SELECT date, count(*) as CountA
     from tableA
     group by date
),
countB as (
     SELECT date, count(*) as CountB
     from tableB
     group by date
)
SELECT A.date, A.CountA, B.CountB
FROM CountA  A
INNER JOIN  CountB B
   ON A.date = B.date

使用表AllDates来解决没有销售的日子

SELECT T.date, 
       CASE 
          WHEN A.CountA IS NULL THEN 0
          ELSE A.CountA
       END as CountA,
       CASE 
          WHEN B.CountB IS NULL THEN 0
          ELSE B.CountB
       END as CountB

FROM AllDates T 
LEFT JOIN CountA  A
       ON T.date = A.date
LEFT JOIN CountB B
       ON T.date = B.date

答案 1 :(得分:0)

select a.dte
      ,a.count a_created
      ,b.count b_created 
from
 (select dte,count(*)from table_a group by dte) a
,(select dte,count(*)from table_b group by dte) b
where b.dte=a.dte

SQLFIDDLE DEMO

<强> OR

您可以使用PostgreSQL的tablefunc

来实现此目的

启动bty创建CREATE EXTENSION if not exists tablefunc;

以及以下为例

create table table_a (dte date,is_created int);
create table table_b (dte date,is_created int);

insert into table_a values('2015-10-07',1);
insert into table_a values('2015-10-07',1);
insert into table_a values('2015-10-07',1);
insert into table_a values('2015-10-07',1);
insert into table_a values('2015-10-07',1);

insert into table_b values('2015-10-07',2);

使用crosstab(),select应为

SELECT *
FROM crosstab(
    'select dte,''a_created'' col,count(*) created from table_a group by dte
    union all
    select dte, ''b_created'' col,count(*) created from table_b group by dte') 
AS ct("date" DATE, "a_created" BIGINT, "b_created" BIGINT);