根据我今天关于这个主题的第一个问题(link),请再向我介绍一下。 我有以下SQL结果:年,季度,月,周和值x值。目前,我每月给出数字1-4。但是,我现在想要花费多达52个连续数字,一个月只能花4个。
即,从以下结果:
year | quarter | month | week | value
2016 | 1 | 1 | 1 | 19738,5
2016 | 1 | 1 | 2 | 19738,5
2016 | 1 | 1 | 3 | 19738,5
2016 | 1 | 1 | 4 | 19738,5
这应该成为:
year | quarter | month | week | value
2016 | 1 | 1 | 1 | 19738,5
2016 | 1 | 1 | 2 | 19738,5
2016 | 1 | 1 | 3 | 19738,5
2016 | 1 | 1 | 4 | 19738,5
2016 | 1 | 2 | 5 | 19738,5
2016 | 1 | 2 | 6 | 19738,5
2016 | 1 | 2 | 7 | 19738,5
2016 | 1 | 2 | 8 | 19738,5
Zu diesem Zeitpunkt lautet die查询所以:
SELECT a.year, a.quarter, a.month, b.week AS week, sum(a.points) AS value
FROM
TABLE AS a,
(SELECT UNNEST(ARRAY[1, 2, 3, 4]) as week) AS b
GROUP BY
year,
quarter,
month,
week;
此外,遗憾的是,我没有任何想法,希望得到您的帮助。
答案 0 :(得分:0)
据我了解,你有12条记录,一个月一个。而且没有日期时间可以提取月,季,周......
我通过将row_number()
添加为周数来修改上一个答案。
请记住:
这不是真正的周数
它每个月除以4,这意味着每年48周。
select year, month, quarter,
row_number() over (partition by year order by year,month,quarter) as week,
value / 4 as week_value
from t1,
(SELECT UNNEST(ARRAY[1, 2, 3, 4])) b;
答案 1 :(得分:0)
你可以将正在运行的一周绑定到正在运行的月份 - 如果在2月开始的一周它属于2月,不管它在3月结束,如果是这样,你可以JOIN
就像这里:
t=# select
wom "week of month", mn "month", wn "week", amount/max(wom) over(partition by mn)
from (
with
weeks as (select generate_series('2016-01-01'::date,'2017-01-01'::date,'1 week'::interval) w)
, months as ( select generate_series('2016-01-01'::date,'2017-01-01'::date,'1 month'::interval) m)
select *, 78954 amount, dense_rank() over (partition by m order by w) wom, dense_rank() over (order by m) mn, dense_rank() over (order by w) wn
from weeks
join months on date_trunc('month',w) = m
) p
;
week of month | month | week | ?column?
---------------+-------+------+----------
1 | 1 | 1 | 15790
2 | 1 | 2 | 15790
3 | 1 | 3 | 15790
4 | 1 | 4 | 15790
5 | 1 | 5 | 15790
1 | 2 | 6 | 19738
2 | 2 | 7 | 19738
3 | 2 | 8 | 19738
4 | 2 | 9 | 19738
1 | 3 | 10 | 19738
2 | 3 | 11 | 19738
3 | 3 | 12 | 19738
4 | 3 | 13 | 19738
1 | 4 | 14 | 15790
2 | 4 | 15 | 15790
3 | 4 | 16 | 15790
4 | 4 | 17 | 15790
5 | 4 | 18 | 15790
1 | 5 | 19 | 19738
2 | 5 | 20 | 19738
3 | 5 | 21 | 19738
4 | 5 | 22 | 19738
1 | 6 | 23 | 19738
2 | 6 | 24 | 19738
3 | 6 | 25 | 19738
4 | 6 | 26 | 19738
1 | 7 | 27 | 15790
2 | 7 | 28 | 15790
3 | 7 | 29 | 15790
4 | 7 | 30 | 15790
5 | 7 | 31 | 15790
1 | 8 | 32 | 19738
2 | 8 | 33 | 19738
3 | 8 | 34 | 19738
4 | 8 | 35 | 19738
1 | 9 | 36 | 15790
2 | 9 | 37 | 15790
3 | 9 | 38 | 15790
4 | 9 | 39 | 15790
5 | 9 | 40 | 15790
1 | 10 | 41 | 19738
2 | 10 | 42 | 19738
3 | 10 | 43 | 19738
4 | 10 | 44 | 19738
1 | 11 | 45 | 19738
2 | 11 | 46 | 19738
3 | 11 | 47 | 19738
4 | 11 | 48 | 19738
1 | 12 | 49 | 15790
2 | 12 | 50 | 15790
3 | 12 | 51 | 15790
4 | 12 | 52 | 15790
5 | 12 | 53 | 15790
(53 rows)