如何在Postgres中加入行?

时间:2017-05-09 03:23:52

标签: postgresql

我在Postgres中有一个预订表,我希望生成一个每月有一行的表格,并在一列中显示每年的收入(以及其他许多遗漏的内容)。

我可以通过硬编码年来做到这一点,但必须有更好的方法。如何将其缩放到x年?

谢谢!

CREATE TABLE reservations (
    checkin date NOT NULL,
    earnings integer
-- other data fields omitted 
  );

CREATE OR REPLACE FUNCTION compareYears()
RETURNS TABLE(month double precision, earnings_2016 bigint, earnings_2017 bigint)
AS
$$
BEGIN
RETURN QUERY
with 
r2017 as (SELECT
  date_part('month', reservations.checkin) AS month,
  sum(reservations.earnings) as earnings_2017
  FROM cd.reservations
  WHERE date_part('year', reservations.checkin) = 2017
  GROUP by date_part('month', reservations.checkin)),
r2016 as (SELECT
  date_part('month', reservations.checkin) AS month,
  sum(reservations.earnings) as earnings_2016
  FROM cd.reservations
  WHERE date_part('year', reservations.checkin) = 2016
  GROUP by date_part('month', reservations.checkin))
SELECT r2017.month, r2016.earnings_2016, r2017.earnings_2017
FROM r2016, r2017
WHERE r2017.month = r2016.month;
END;
$$
LANGUAGE 'plpgsql' VOLATILE;

1 个答案:

答案 0 :(得分:0)

看看crosstab。我认为它正是你所需要的。 这是一个example