我有兩個獨立的客戶表A和B.我試圖計算按日期在同一查詢中創建的客戶A和B.我可以通過Union All獲得正確的數據,但沒有正確分組。在Postgresql的共享日期計數兩個表
我想要的數據,像這樣:
date,count A created, count B created
4/15/2015,1,5
相反的:
date, count
4/15/2015, 1
4/15/2015, 5
感謝幫助!
我有兩個獨立的客戶表A和B.我試圖計算按日期在同一查詢中創建的客戶A和B.我可以通過Union All獲得正確的數據,但沒有正確分組。在Postgresql的共享日期計數兩個表
我想要的數據,像這樣:
date,count A created, count B created
4/15/2015,1,5
相反的:
date, count
4/15/2015, 1
4/15/2015, 5
感謝幫助!
只要使用一個cte,只需要小心,如果你沒有在每一天的日期。在這種情況下,如果沒有銷售,你需要一個日期表來獲得0。
也儘量不要使用保留字像date
作爲FIELDNAMES
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
與cte的第一個建議像一個魅力工作! –
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
OR
您可以使用使用PostgreSQL的tablefunc
開始BTY創建CREATE EXTENSION if not exists tablefunc;
,並通過使用crosstab()
以下作爲一個例子
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);
實現這一目標的選擇應該是
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);
嗨翅黑豹,會試試看!謝謝您的幫助。 –