0
我在Postgres中有一張預留表,我想要生成一個每月有一行的表格,並在列中顯示每年的收入(以及爲簡單起見,此處省略了很多其他內容)。如何在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;
這可能很愚蠢,但你爲什麼不創建一個年份的日曆表呢?那樣你可以在一年加入,不是嗎? – Arkhena