することができます使用次のいずれか
SELECT
*
FROM
crosstab(
$$
SELECT "Source", "Date"::text, count("Date")
FROM t
GROUP BY "Source", "Date"
ORDER BY "Source"
$$,
$$
SELECT cast(d as date)
FROM generate_series(date '2017-06-01', date '2017-06-10', interval '1 day') as s(d)
$$
) AS
(
"Source" text,
"2017-06-01" bigint,
"2017-06-02" bigint,
"2017-06-03" bigint,
"2017-06-04" bigint,
"2017-06-05" bigint,
"2017-06-06" bigint,
"2017-06-07" bigint,
"2017-06-08" bigint,
"2017-06-09" bigint,
"2017-06-10" bigint
) ;
のPostgreSQL固有のcrosstab(text source_sql, text category_sql)
を使用し、それがtablefunc
拡張を必要とするか、 "古典SQLのピボット" 行くことができます:
SELECT
"Source"
,COUNT(CASE WHEN "Date" = '2017-06-01' THEN 1 END) AS "2017-06-01"
,COUNT(CASE WHEN "Date" = '2017-06-02' THEN 1 END) AS "2017-06-02"
,COUNT(CASE WHEN "Date" = '2017-06-03' THEN 1 END) AS "2017-06-03"
,COUNT(CASE WHEN "Date" = '2017-06-04' THEN 1 END) AS "2017-06-04"
,COUNT(CASE WHEN "Date" = '2017-06-05' THEN 1 END) AS "2017-06-05"
,COUNT(CASE WHEN "Date" = '2017-06-06' THEN 1 END) AS "2017-06-06"
,COUNT(CASE WHEN "Date" = '2017-06-07' THEN 1 END) AS "2017-06-07"
,COUNT(CASE WHEN "Date" = '2017-06-08' THEN 1 END) AS "2017-06-08"
,COUNT(CASE WHEN "Date" = '2017-06-09' THEN 1 END) AS "2017-06-09"
,COUNT(CASE WHEN "Date" = '2017-06-10' THEN 1 END) AS "2017-06-10"
FROM
t
GROUP BY
"Source"
ORDER BY
"Source" ;
Source | 2017-06-01 | 2017-06-02 | 2017-06-03 | 2017-06-04 | 2017-06-05 | 2017-06-06 | 2017-06-07 | 2017-06-08 | 2017-06-09 | 2017-06-10
:----- | ---------: | ---------: | ---------: | ---------: | ---------: | ---------: | ---------: | ---------: | ---------: | ---------:
Banner | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0
Email | 2 | 0 | 3 | 1 | 0 | 2 | 1 | 0 | 0 | 0
を
どちらも同じ値を返します。違いは2番目に「0」、最初にはカウントする値がない場合は「null」を返します。
dbfiddle here
あなたはどのように多くの日付の列が必要なのですか?それは固定ですか? –
列は固定されていません。おそらくすべての値のjsonである単一の列を返すこともできますが、その日付のレコードがない場合はゼロ値を持つ必要があります。 –