简体   繁体   English

sql查询记录对两个

[英]sql query records pair of two

I have a table like this one below where the records are basically pair of two (same ID1 and ID2) but different Note and Status (some times). 我有一个像下面这样的表,其中记录基本上是两对(相同的ID1和ID2)但不同的注意和状态(有时)。 I need to select all the records that at the same time have the field Note equal to "Ready to QC" and the field Status equal to 1, and the records with the field Note equal to "Ready for Cataloging" have Status 0. 我需要选择同时具有等于“Ready to QC”字段的所有记录,并且字段Status等于1,并且字段Note等于“Ready for Cataloging”的记录具有状态0。

ID1,   ID2,      Note,                      Status
3,     22,       Ready for QC,                1
3,     22,       Ready for Cataloging,        0
36,    22,       Ready for QC,                1
36,    22,       Ready for Cataloging,        1
63,    22,       Ready for QC,                1
63,    22,       Ready for Cataloging,        0
67,    67,       Ready for QC,                0
67,    67,       Ready for Cataloging,        0

Any suggestions? 有什么建议? Thank you. 谢谢。 Giovanni 乔瓦尼

I think you want all the ID1 and ID2 of such records where both conditions exist.. 我想你想要这两个条件存在的所有记录的ID1和ID2。

It does assume a uniqueness for each ID1, ID2, Note, Status (meaning there can't be two identical records in the table) 它假定每个ID1,ID2,Note,Status的唯一性(意味着表中不能有两个相同的记录)

SELECT ID1, ID2, count(*) cnt
FROM Table
WHERE (Note = "Ready to QC" and status = 1) 
    OR(note = "Ready for Cataloging" and Status 0)
GROUP BY ID1, ID2
HAVING COUNT(*) = 2

This one is longer but accounts for duplicates: 这个更长但是重复:

SELECT t1.id1, t1.id2, t1.note, t1.status
FROM
(SELECT *
 FROM t
 WHERE note = 'Ready for QC'
 AND status = 1) t1
INNER JOIN
(SELECT *
 FROM t
 WHERE note = 'Ready for Cataloging'
 AND status = 0) t2
ON t1.id1 = t2.id1
AND t1.id2 = t2.id2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM