我有一张这样的表:
SchoolName|SchoolID
--------------------
School A |x
School B |x
School C |y
School D |z
School D |z
实际上有更多列,包括唯一ID。以上只是为了简洁。
我需要做的是选择所有列,其中SchoolID出现多次,但前提是SchoolName列中的相应值不是。
所以我想获得学校A和学校B的行的所有列,但不是学校C和学校D行。
db是MS SQL 2008 R2。
最初的问题非常困惑,希望我现在能够正确地改写它!
答案 0 :(得分:1)
您可以使用COUNT
的窗口版来计算SchoolID
和SchoolName
出现次数:
SELECT *
FROM (
SELECT *,
COUNT(*) OVER (PARTITION BY SchoolID) AS cntSchoolID,
COUNT(*) OVER (PARTITION BY SchoolID, SchoolName) AS cntSchoolName
FROM mytable ) t
WHERE t.cntSchoolID > 1 AND t.cntSchoolName = 1
答案 1 :(得分:0)
你想要这样的东西吗?
SELECT A.*
FROM yourTable A
CROSS APPLY (
SELECT TOP 1 NULL col
FROM yourTable
WHERE A.SchoolID = SchoolID
AND A.SchoolName = SchoolName
GROUP BY SchoolID,SchoolName
HAVING COUNT(*) > 1
) CA
答案 2 :(得分:0)
我会建立一个重复的所有学校名单,以及所有重复的学校名单,然后拉出学校名称或学校所在的所有行:
select
*
from
mytable
where
(schoolname in
(
select schoolname
from
mytable
group by schoolname
having count (*) > 1)
OR
schoolid in
(
select
schoolid
from
mytable
group by schoolid
having count (*) > 1)
)
丑陋,但我认为它会给你你想要的结果。