2011-02-02 55 views
1

我有如下表:SQL Server組問號

CREATE TABLE #weeks(
    ProposalLineWeekID INT, 
    StartWeek DATETIME, 
    EndWeek DATETIME, 
    Selected BIT, 
    WeekNumber INT 
) 

如何獲取所有具有重複WeekNumberProposalLineWeekID值? 例如

ProposalLineWeekID, WeekNumber 
------------------------------ 
2     22 
3     6 
4     22 

我想獲得ProposalLineWeekID 2和4伴隨WeekNumber。

回答

4

試試這個:

SELECT ProposalLineWeekID, WeekNumber 
FROM #Weeks 
WHERE WeekNumber IN 
( 
    SELECT WeekNumber 
    FROM #weeks 
    GROUP BY WeekNumber 
    HAVING COUNT(*) > 1 
) 

子查詢中找出所有重複的星期數和外部查詢取出相應行。

+0

+1,這也能發揮作用。不知道我的或你的解決方案哪一個在實踐中表現會更好。 – 2011-02-02 18:53:32

2

如果我理解正確的話,我想這是你想要什麼:

SELECT DISTINCT w1.ProposalLineWeekID, w1.WeekNumber 
FROM weeks w1 
INNER JOIN weeks w2 ON w2.WeekNumber = w1.WeekNumber 
    AND w2.ProposalLineWeekID <> w1.ProposalLineWeekID 
+0

+1,但你可能想要在給定週數重複兩次以上的情況下將WeekNumber(OP要求的)和DISTINCT添加到`SELECT`子句 – 2011-02-02 18:49:29