SQL Server组BY问题

时间:2011-02-02 18:40:10

标签: sql sql-server sql-server-2005 tsql group-by

我有下表:

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

如何获取具有重复ProposalLineWeekID条目的所有WeekNumber值? 例如

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

我想通过附带的WeekNumber获得ProposalLineWeekID 2和4。

2 个答案:

答案 0 :(得分:4)

试试这个:

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

子查询查找所有重复的周数,外部查询获取相应的行。

答案 1 :(得分:2)

如果我理解正确,我认为这就是你想要的:

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