用于捕获具有不同ID的类似行的SQL语句

时间:2011-05-11 14:31:27

标签: sql sql-server sql-server-2005

我有一张桌子:

term_id    course_id

1          592
1          603
2          592
2          603
2          700

如何创建查询以选择术语1和2中的所有course_id?

4 个答案:

答案 0 :(得分:8)

SELECT course_id
FROM T 
WHERE term_id=1
INTERSECT
SELECT course_id
FROM T 
WHERE term_id=2

或者

SELECT course_id
FROM T 
WHERE term_id IN (1,2)
GROUP BY course_id
HAVING COUNT(DISTINCT term_id) = 2

答案 1 :(得分:1)

SELECT * INTO #TEMP1
FROM T
WHERE TERM_ID = 1

SELECT * INTO #TEMP2
FROM T
WHERE TERM_ID = 2

SELECT DISTINCT COURSE_ID
FROM #TEMP1
WHERE COURSE_ID IN (SELECT DISTINCT COURSE_ID FROM #TEMP2)

答案 2 :(得分:1)

Martin的答案简明扼要,但我会提出两种方法,这些方法可能更容易解析,具体取决于您习惯阅读的内容。

不对您的架构做任何假设:

SELECT DISTINCT
  course_id
FROM
  MyTable AS T1
WHERE
      term_id = 1
  AND EXISTS (SELECT * FROM MyTable AS T2 WHERE T1.course_Id = T2.course_id AND T2.term_id = 2)

如果像我预期的那样{course_id,term_id}是唯一的,那么你也可以这样做:

SELECT
  T1.course_id
FROM
  MyTable AS T1
  INNER JOIN MyTable AS T2 ON T1.course_id = T2.course_id
WHERE
      T1.term_id = 1
  AND T2.term_id = 2

答案 3 :(得分:1)

更一般的情况,以多个术语获得所有课程:

select course_id
from foo
group by course_id
having count(term_id) > 1