2017-08-21 61 views
0

我無法找到比較某個表(表1)中的數據的方法。表1的SQL - 比較一個表中的數據

Date  ID  Item   
----  ------- ----- 
2017-06-30 90  2200 
2017-06-30 150  1200 
2017-06-30 150  1201 
2017-06-30 150  1202 
2017-06-30 150  1203 
2017-06-30 150  1204 
2017-07-31 150  1201 
2017-07-31 150  1202 
2017-07-31 150  1203 
2017-07-31 150  1204 
2017-07-31 150  1205 
2017-07-31 90  2200 

結果的

部分我想得到的是1205,因爲這是在下個月舉行新的項目。如果我能得到在接下來的一個月內不會再出現的物品,那也不錯,如:1200

**編輯:我應該提到的一件事是Table1在ID列中也有不同的ID。所以主要目標是比較確切的ID = 150(不是160或180)。 **

我將不勝感激任何意見。

謝謝

+0

@ADyson這足以清楚,我;-) – Strawberry

回答

0

如:

SELECT x.* 
    FROM my_table x 
    LEFT 
    JOIN my_table y 
    ON y.id = x.id 
    AND y.date = '2017-06-30' 
    AND y.item = x.item 
WHERE x.date = '2017-07-31' 
    AND y.id IS NULL; 

SELECT x.* 
    FROM my_table x 
    LEFT 
    JOIN my_table y 
    ON y.id = x.id AND y.date = x.date - INTERVAL 1 MONTH 
    AND y.item = x.item 
WHERE x.date = '2017-07-31' 
    AND y.id IS NULL; 

I本來應該把剩下的部分作爲讀者的練習,但是我看到我的計劃已經陷入困境。

+0

非常感謝!我會嘗試自己寫,並理解它。我還添加了一行,可以選擇我想查看的確切ID。 – michal2805

+0

@ michal2805請注意,實際上有一種在SO上表達感謝的機制。只是在說'。 – Strawberry

0

要選擇沒有被列入前幾個月或前幾個月都是退休的項目...

select 'new item' as result_type, item 
from MyTable a1 
where not exists 
(
select 1 
from MyTable a2 
where a1.item = a2.item 
and a2.Date < a1.date -- change this to a date function to compare to previous month only 
) 
union all 
select 'retired item' as result_type, item 
from MyTable a1 
where not exists 
(
select 1 
from MyTable a2 
where a1.item = a2.item 
and a2.Date > a1.date -- change this to a date function to compare to previous month only 
) 
+0

謝謝你的答覆,我將嘗試在閱讀本我自己的。 我應該提到的一件事是Table1在ID列中也有不同的ID。 所以主要目標是比較確切的ID = 150(不是160或180)。 – michal2805

1

如果你想同時在一個月內和「刪除」的郵件「新」項目:

select 'new', t.* 
from t 
where not exists (select 1 
        from t t2 
        where t2.item = t.item and 
         year(t2.date) = year(t.date - interval 1 month) and 
         month(t2.date) = month(t.date - interval 1 month) 
       ) 
union all 
select 'deleted', t.* 
from t 
where not exists (select 1 
        from t t2 
        where t2.item = t.item and 
         year(t2.date) = year(t.date + interval 1 month) and 
         month(t2.date) = month(t.date + interval 1 month) 
       );