我试图从我们的一个数据库表中提取与“G”类型(G GAR GER GR)匹配的特定类型研究的频率以及该周的研究总数(匹配所有类型)和'G'的相对频率。我希望将输出分组为几周(从星期一开始到星期五结束)。
我使用generate_series
在感兴趣的时段内获得一系列星期一
SELECT (current_date- cast(extract(dow from current_date) as int) + 1) - s.a AS dates FROM generate_series(0,182,7) AS s(a);
使用以下命令
FROM (SELECT (current_date- cast(extract(dow from current_date) as int) + 1) - s.a AS dates FROM generate_series(0,182,7) AS s(a)) d
LEFT JOIN study ON
study_date <= d.dates
WHERE study_name ~ 'T(C|L)S' and study_type ~'G'
GROUP BY 1
ORDER BY 1;
我得到以下输出
dates | count
------------+-------
26/06/2017 | 6
03/07/2017 | 11
10/07/2017 | 15
17/07/2017 | 30
24/07/2017 | 38
31/07/2017 | 47
07/08/2017 | 61
14/08/2017 | 77
这给我一个正确的滚动计数,因为我们对'G'类型进行了更多的研究。但是,我尝试以下操作将其拆分为每周范围
SELECT d.dates, count(*)
FROM (SELECT (current_date- cast(extract(dow from current_date) as int) + 1) - s.a AS dates FROM generate_series(0,182,7) AS s(a)) d
LEFT JOIN study ON
study_date >= d.dates
WHERE study_name ~ 'T(C|L)S' and study_type ~ 'G' AND study_date <= myo_date + interval '5' day
GROUP BY 1
ORDER BY 1;
给出了我不理解的输出(我期待上面输出中行之间的差异)
dates | count
------------+-------
13/02/2017 | 79
20/02/2017 | 79
27/02/2017 | 79
06/03/2017 | 79
13/03/2017 | 79
20/03/2017 | 79
27/03/2017 | 79
03/04/2017 | 79
10/04/2017 | 79
17/04/2017 | 79
24/04/2017 | 79
01/05/2017 | 79
08/05/2017 | 79
15/05/2017 | 79
22/05/2017 | 79
29/05/2017 | 79
05/06/2017 | 79
12/06/2017 | 79
19/06/2017 | 79
26/06/2017 | 74
03/07/2017 | 70
10/07/2017 | 68
17/07/2017 | 53
24/07/2017 | 44
31/07/2017 | 34
07/08/2017 | 22
14/08/2017 | 3
如何每周获得计数?另外,如何在study_type可以是任何内容的情况下添加额外的列总计数。
预期输出
dates | count
------------+-------
26/06/2017 | 6
03/07/2017 | 5
10/07/2017 | 4
17/07/2017 | 15
24/07/2017 | 8
31/07/2017 | 9
07/08/2017 | 14
14/08/2017 | 16
答案 0 :(得分:0)
您可以尝试在此使用LAG()
:
WITH cte AS (
SELECT
(current_date- cast(extract(dow from current_date) as int) + 1) - s.a AS dates,
COUNT(*) AS cnt
FROM generate_series(0,182,7) AS s(a)) d
LEFT JOIN study
ON study_date <= d.dates
WHERE study_name ~ 'T(C|L)S' and study_type ~'G'
GROUP BY 1
)
SELECT
dates,
cnt - LAG(cnt, 0) OVER (ORDER BY dates)
FROM cte;