[英]How to find pairs in SQL
I have a table containing original records and cancelled records. 我有一个包含原始记录和已取消记录的表。 The original records are marked with code=1 and the cancelled ones are marked with code=2. 原始记录用代码= 1标记,已取消的记录用代码= 2标记。 There are other types of codes as well. 还有其他类型的代码。 I need to find all the original records that do not have a cancellation record in the table. 我需要查找表中没有取消记录的所有原始记录。
Eg Table1 例如表1
id | column2 | column3 | code
-- |-------- | ------- | ---
1 | abc | def | 1
2 | xyz | pqr | 1
3 | abc | def | 2
The result of the query should be the row with id 2 as it has not been cancelled. 查询的结果应该是ID为2的行,因为它尚未被取消。
I am trying to use self-join 我正在尝试使用自我加入
select *
from table1 t1
join table1 t2 on t1.column1=t2.column1
and t1.column2=t2.column2
and t1.code<t2.code
where not (t1.code=1 and t2.code=2)
SELECT *
FROM table1 AS t1
WHERE code = 1
AND NOT EXISTS ( SELECT *
FROM table1 t2
WHERE t2.code = 2
AND t2.column2 = t1.column2
AND t2.column3 = t1.column3 )
This answer is preferable to using NOT EXISTS
becauese it avoids a correlated subquery. 这个答案比使用NOT EXISTS
更好,因为它避免了相关的子查询。 It also uses joins, which means it can take advantage of indices. 它还使用联接,这意味着它可以利用索引。
SELECT t1.id,
t1.column2,
t1.column3,
t1.code
FROM table1 t1
INNER JOIN
(
SELECT column2,
column3
FROM table1
GROUP BY column2,
column3
HAVING SUM(CASE WHEN code = 2 THEN 1 ELSE 0 END) = 0
) t2
ON t1.column2 = t2.column2 AND
t1.column3 = t2.column3
You can use CTE. 您可以使用CTE。 Find sum of code as it is integer. 查找代码和,因为它是整数。 If it is greater than 1, it means somewhere for this value there is 2. 如果大于1,则表示该值的某个位置为2。
;WITH CTE AS
(
Select column1,column3 from Table1
GROUP BY column1,column3
HAVING SUM(code)=1
)
SELECT t.id,CTE.* FROM CTE
INNER JOIN @temp t ON t.column1=CTE.column1 AND t.column3=CTE.column3
Please let me know if it helps. 请告诉我是否有帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.