2017-08-21 62 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) 
       );