交叉連接可以是很難,因爲它們涉及的方式,通常是直觀的數據來工作。下面是我會怎麼做它,而不是,用簡單的,默認情況下,INNER JOIN
:
WITH day1_info AS
(SELECT sub1, sub2
FROM mytable)
SELECT
day2_info.sub1 - day1_info.sub1 AS sub1_difference,
day2_info.sub2 - day1_info.sub2 AS sub2_difference,
FROM
mytable AS day2_info JOIN day1_info
ON day1_info.date = '2014-11-07'
AND day2_info.date = '2014-11-08'
如果你想多套日期做到這一點,你可以做到這一點。只需稍微更改JOIN
聲明即可。 (請注意,在這種情況下,您可能還需要SELECT
其中一個日期,以便您知道每個結果適用於哪個時間段。)
WITH day1_info AS
(SELECT sub1, sub2
FROM mytable)
SELECT
day2_info.date,
day2_info.sub1 - day1_info.sub1 AS sub1_difference,
day2_info.sub2 - day1_info.sub2 AS sub2_difference,
FROM
mytable AS day2_info JOIN day1_info
ON (day1_info.date::timestamp + '1 day') = day2_info.date::timestamp