[英]SQL server: Compare rows
I need a query which can do the following operation. 我需要一个可以执行以下操作的查询。 I have a table with 2 columns
我有一张两列的桌子
ID Values
1 1
1 2
1 3
1 4
2 2
2 5
2 6
if you see for ID 1 I have 1,2,3 and 4 as values and for ID 2 I have 2, 5 and 6. 如果您看到ID 1,我有1,2,3和4作为值,ID 2我有2,5和6。
I want to write a query which return the following 我想写一个查询,返回以下内容
1(-) 4(-) 5(+) 6(+) 1(-)4(-)5(+)6(+)
mean 1 and 4 are deleted and 5 and 6 are added by comparing the two ids. 通过比较两个id,删除均值1和4,并添加5和6。
Is it possible? 可能吗? Please let me know
请告诉我
Thanks 谢谢
Something like: 就像是:
(
SELECT T.Value FROM dbo.Table T WHERE T.ID = 1
EXCEPT
SELECT T.Value FROM dbo.Table T WHERE T.ID = 2
)
UNION
(
SELECT T.Value FROM dbo.Table T WHERE T.ID = 2
EXCEPT
SELECT T.Value FROM dbo.Table T WHERE T.ID = 1
)
That will get you the list of values that are associated with 1 but not 2, and 2 but not 1. You could easily multiply the values from one of those subqueries by -1 to differentiate them, or run them as two separate queries. 这将为您提供与1而不是2和2而不是1关联的值的列表。您可以轻松地将其中一个子查询的值乘以-1以区分它们,或将它们作为两个单独的查询运行。
This will give you 1 & 4: 这将给您1和4:
select a.values
from my_table a
where not exists (
select * from my_table b where b.values = a.values and b.ID = 2)
and a.ID = 1
and this will give you 5 & 6: 这将给您5&6:
select a.values
from my_table a
where not exists (
select * from my_table b where b.values = a.values and b.ID = 1)
and a.ID = 2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.