比较同一个表中的行

时间:2016-09-01 18:42:51

标签: mysql

id      Status      Material    Week
-------------------------------------
a1      Clear       iron        33
a1      Clear       iron        34
a1      Shipped     iron        35
b1      Cancel      Brass       33
b1      Cancel      Brass       34
b1      Cancel      Brass       35
c1      Identify    Plastic     34
c1      Clear       Plastic     35

您好,我正在尝试提出一个查询,我可以选择状态或材料在第34周和第35周之间发生变化的所有ID。如果在第33周和第34周或第33周和第35周之间发生任何变化,请忽略它。此外,如果在第33周或第34周没有出现但在第35周出现的任何东西,则必须包括在内。最后,ID应该是唯一的。

到目前为止,我已经提出了以下问题。

SELECT DISTINCT t1.id
FROM table t1
JOIN table t2
ON t1.id = t2.id
WHERE t1.Status<>t2.Status or t1.Material<>t2.Material

预期结果:

id
a1
c1

3 个答案:

答案 0 :(得分:0)

您可以使用计数(如果行更改您的行数超过ID)

select t.id from (
   select distinct id, status, material 
   from mytable 
   where week in (33,34,35) ) t
group by t.id 
having count(*) >1; 

最终如果一周是字符串尝试使用

select t.id from (
   select distinct id, status, material 
   from mytable 
   where week in ('33','34','35') ) t
group by t.id 
having count(*) >1; 

答案 1 :(得分:0)

这个怎么样?

SELECT 
 T1.id
FROM t T1
LEFT JOIN t T2 ON T1.id = T2.id  
AND T2.Week = 34 
WHERE T1.Week = 35
AND IF(T2.id IS NULL, TRUE, ((T1.Status <> T2.status) OR (T1.Material <> T2.Material)))

Demo here

只需要两个T1 (row for week #35)T2 (row for week #34)

实例
T2.week = 34

T1.week = 35

如果周#34 的行存在,那么statusmaterial T1T2必须有所不同才能出现在输出中。 请参阅上述查询中的IF语句

<强>测试

create table t(
  id varchar(10),
  Status varchar(10),
  Material varchar(10),
  week int
  );

INSERT INTO t(id,status,material,week)
VALUES('a1','clear','iron',33),
('a1','clear','iron',34),
('a1','shipped','iron',35),
('b1','cancel','brass',33),
('b1','cancel','brass',34),
('b1','cancel','brass',35),
('c1','identify','plastic',34),
('c1','clear','plastic',35);

<强>输出:

id
a1
c1

答案 2 :(得分:0)

这个谜题的最后一部分留给读者练习......

SELECT x.*, y.*
  FROM my_table x
  LEFT
  JOIN my_table y
    ON y.id = x.id
   AND (y.status = x.status AND y.material = x.material)
   AND y.week = 35
 WHERE x.week = 34;