2013-02-17 135 views
1

我需要幫助來查詢一個表,我需要使用兩個不同列來比較兩行。如何比較兩行/多行的兩個不同列

如:

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的行。

我需要使用單個查詢來獲得這兩件事情。 請幫忙。

+0

按兩列分組... EmpidNum Group,EmpAddNum – Mate 2013-02-17 09:50:39

+2

我不明白你的意思。第一種情況下你在說什麼ID?根據示例數據,你想要什麼結果? – Guffa 2013-02-17 09:54:50

+0

向我們展示您的理想結果 – 2013-02-17 11:11:42

回答

1

關鍵是要爲同一個表創建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 

其他我給出的答案好多了。看看它

0

如果你想超過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 
0

,如果我理解正確你的問題馬赫,在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 

演示SQLFiddle