如何比较两行/多行的两个不同列
问题描述:
我需要帮助来查询一个表,我需要使用两个不同列来比较两行。如何比较两行/多行的两个不同列
如:
EMP Table
EmpId EmpName EmpIDNum EmpAddNum
1 xyz 123 456
2 wer 345 123
3 qwe 478 908
4 ghe 123 567
5 fde 456 123
这里在上表中,我需要寻找具有相同的ID号的行(这可以通过使用group by
子句来完成),我找了如何得到两个其中一行的EmpIDNum是其他行的EmpAddNum的行。
我需要使用单个查询来获得这两件事情。 请帮忙。
答
关键是要为同一个表创建2个别名并对其进行操作。
create table #temp(ID int, num1 int, num2 int)
insert into #temp values (1,123,234)
insert into #temp values (2,234,345)
insert into #temp values (3,345,123)
--query just to create a dummy table fro your reference
--main query starts from here
select * from #temp where ID in
((select t1.id from #temp t1, #temp t2
where t1.num1 = t2.num2 and t1.num1 = 123),(select t2.id from #temp t1, #temp t2
where t1.num1 = t2.num2 and t1.num1 = 123))
--sorry for not indenting it
drop table #temp
--returns
--ID num1 num2
-- 1 123 234
-- 3 345 123
其他我给出的答案好多了。看看它
答
如果你想超过1排在第二cloumn然后
create table #temp(ID int, num1 int, num2 int)
insert into #temp values (1,123,234)
insert into #temp values (2,234,345)
insert into #temp values (3,345,123)
insert into #temp values (4,567,123)
--query just to create a dummy table fro your reference
--main query starts from here
select * from #temp where ID in
(select t1.id from #temp t1, #temp t2
where t1.num1 = t2.num2 and t1.num1 = 123) or ID in
(select t2.id from #temp t1, #temp t2
where t1.num1 = t2.num2 and t1.num1 = 123)
--sorry for not indenting it
drop table #temp
--returns
--ID num1 num2
-- 1 123 234
-- 3 345 123
-- 4 567 123
答
,如果我理解正确你的问题马赫,在SQLSerever2005 +你可以试试这个
SELECT t1.EmpID, t1.EmpName, t1.EmpIDNum, t1.EmpAddNum
FROM EMPtbl t1
CROSS APPLY(
SELECT t2.EmpIDNum
FROM EMPtbl t2
GROUP BY t2.EmpIDNum
HAVING COUNT(*) > 1
INTERSECT
SELECT t3.EmpIDNum
FROM EMPtbl t3
WHERE T1.EmpIDNum IN (t3.EmpAddNum, t3.EmpIDNum)
) o
按两列分组... EmpidNum Group,EmpAddNum – Mate 2013-02-17 09:50:39
我不明白你的意思。第一种情况下你在说什么ID?根据示例数据,你想要什么结果? – Guffa 2013-02-17 09:54:50
向我们展示您的理想结果 – 2013-02-17 11:11:42