Postgresql:分割成4行

时间:2016-12-16 09:26:52

标签: sql postgresql

我担心的是使用SQL脚本将一行拆分为4行。 这是我在SQL结果中得到的年份,季度,月份和x值得的值。现在我还想花一个月的时间(1-4),而不必将其添加为表格的列。 同样,该值应除以4。 因此,从这个结果:

year | quarter | month | value
2016 | 1       | 1     | 78954

结果:

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

我不知道如何实现这一点。 我希望有人能帮助我。

祝你好运

4 个答案:

答案 0 :(得分:2)

您可以通过笛卡尔联合来实现:

SELECT a.year, a.quarter, a.month, b.week, a.value
  FROM a, (SELECT UNNEST(ARRAY[1, 2, 3, 4]) as week) b

答案 1 :(得分:0)

只需使用union

select year, quarter, month, 1 as week, value / 4 as value
union all
select year, quarter, month, 2 as week, value / 4 as value
union all
select year, quarter, month, 3 as week, value / 4 as value
union all
select year, quarter, month, 4 as week, value / 4 as value

答案 2 :(得分:0)

你也可以使用`generate_series():

select t.year, t.quarter, t.month, w.week, t.value / 4
from the_table t
 cross join generate_series(1,4) as w(week)
order by t.year, t.quarter, w.week;

如果您需要更改所需的重复行数,使用generate_series()会更灵活 - 尽管“每季度一周”并不需要这种灵活性。

答案 3 :(得分:0)

或者你可以用非常科学的方式来做: - )

WITH series as (select generate_series(1,4,1) as week ),
  data as (SELECT 2016 as year, 1 as quarter, 1 as month, 78954 as value)
  SELECT d.year, d.quarter, d.month, s.week, d.value/(SELECT count(*) FROM series)::numeric 
  FROM data d JOIN series s ON true