我有一张桌子“产品”,我每天都有产品价格,现在我想知道昨天出现的产品哪些是昨天出现的产品,如果两天都存在,那么什么是价格变化的差异。
例如表“产品”:
locale productID price date
US pro1 100 2015-04-02
US pro2 200 2015-04-02
CA pro1 100 2015-04-02
US pro1 110 2015-04-01
US pro3 500 2015-04-01
CA pro4 100 2015-04-01
所以期望的输出应该是: -
locale_t|productID_t|price_t|date_t|locale_y|productID_y|price_y|date_y|change
US pro1 100 2015-04-02 US pro1 110 2015-04-01 10
US pro2 200 2015-04-02 REMOVED 200
REMOVED US pro3 500 2015-04-01 500
CA pro1 100 2015-04-02 REMOVED 100
REMOVED CA pro4 100 100
其中locale_t表示locale_today,locale_y表示locale_yesterday。 所以我可以清楚地告诉我们昨天删除了多少产品以及今天增加了多少产品。
答案 0 :(得分:1)
你想要一个自我交叉连接,但是你真的加入了两个不同的子集,这很复杂。
为实现这一点,一种方法是在同一数据上连接两个子查询,例如: http://sqlfiddle.com/#!15/2d6ae/15:
SELECT
coalesce(yesterday.locale, today.locale) AS locale,
coalesce(yesterday."productID", today."productID") AS "productID",
today.date AS date_t,
today.price AS price_t,
yesterday.date AS date_y,
yesterday.price AS price_y,
today.price - yesterday.price AS "change"
FROM (
SELECT * FROM Table1 WHERE "date" = '2015-04-01'
) AS yesterday
FULL OUTER JOIN (
SELECT * FROM Table1 WHERE "date" = '2015-04-02'
) AS today
ON (today."locale" = yesterday."locale"
AND today."productID" = yesterday."productID")
ORDER BY 1, 2;
locale | productID | date_t | price_t | date_y | price_y | change
--------+-----------+------------+---------+------------+---------+--------
CA | pro1 | 2015-04-02 | 100 | | |
CA | pro4 | | | 2015-04-01 | 100 |
US | pro1 | 2015-04-02 | 100 | 2015-04-01 | 110 | -10
US | pro2 | 2015-04-02 | 200 | | |
US | pro3 | | | 2015-04-01 | 500 |
(5 rows)
预期的结果并不完全相同,但你并没有真正尝试用文字指明你想要什么,我不想猜测。
我怀疑您可能希望在coalesce
列中使用change
来生成null结果,例如:
coalesce(today.price - yesterday.price, today.price, -yesterday.price) AS "change"