要求:用一條SQL語句查出所有課程均為85以上的姓名,若缺考則無記錄
/*
XM KeCheng FenShu
-------- -------------------- -----------
張三 語文 88
張三 數學 91
李四 英語 90
李四 語文 88
李四 數學 100
王五 數學 79
王五 語文 60
其正確結果:李四
*/
--測試環境
declare @tbl TABLE (XM [varchar](8),KeCheng [varchar](20),FenShu [int])
insert into @tbl
select '張三','語文',88 union all select
'張三','數學',91 union all select
'李四','英語',90 union all select
'李四','語文',88 union all select
'李四','數學',100 union all select
'王五','數學',79 union all select
'王五','語文',60
--查詢:一條SQL語句哦
--方法一:
SELECT XM
FROM @tbl
WHERE FENSHU>=85
GROUP BY XM
HAVING COUNT(XM)=(SELECT TOP 1 COUNT(DISTINCT KECHENG) FROM @tbl)
--方法二:
select xm from @tbl where xm in
(
select xm from @tbl group by xm having min(FenShu)>=85
)
group by xm having(count(xm)) = (select count(distinct KeCheng) from @tbl)
--方法三:
SELECT distinct xm FROM @tbl a
WHERE NOT EXISTS
(
SELECT KeCheng FROM
(
SELECT DISTINCT KeCheng FROM @tbl
)b
WHERE NOT EXISTS
(
SELECT * FROM @tbl c
WHERE a.XM=c.XM
AND b.KeCheng=c.KeCheng
AND c.FenShu>=85
)
)
/*結果:
XM
--------
李四
*/

浙公网安备 33010602011771号