SQL - 比较一个表中的数据

时间:2017-08-21 09:55:31

标签: mysql sql

我无法找到比较一个表格的方法(表1)。

表1的一部分

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)。 **

我将不胜感激任何建议。

谢谢

3 个答案:

答案 0 :(得分: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)
                 );

答案 1 :(得分: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
)

答案 2 :(得分:0)

E.g:

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;

我会把剩下的部分作为练习留给读者,但我看到我的计划已被打破。