从这样的表格中:
Name | Score
------ | ------
Bill | 1
Bill | 2
Bill | 1
Steve | 1
Steve | 4
Steve | 1
返回从未得分超过3的人的姓名
答案是:
Name |
------ |
Bill |
答案 0 :(得分:2)
关键是获得每个人的最高分,然后过滤到最大值小于3的人。要获得最大值,您需要进行汇总(GROUP BY
和MAX
)。然后,要将过滤器应用于聚合,您必须使用HAVING
而不是WHERE
。所以你最终会得到:
SELECT Name, MAX(Score) AS HighScore
FROM Table
GROUP BY Name
HAVING MAX(Score) <= 3;
答案 1 :(得分:1)
一个解决方案是:
SELECT DISTINCT name
FROM mytable
WHERE Name NOT IN
( SELECT Name
FROM mytable
WHERE score > 3
)
答案 2 :(得分:0)
2017-06-14
答案 3 :(得分:0)
样本表:
DECLARE @Table1 TABLE
(Name varchar(5), Score int)
;
INSERT INTO @Table1
(Name, Score)
VALUES
('Bill', 1),
('Bill', 2),
('Bill', 1),
('Steve', 1),
('Steve', 4),
('Steve', 1)
;
脚本:
;with CTE AS (
select Name,Score from @Table1
GROUP BY Name,Score
HAVING (Score) > 3 )
Select
NAME,
Score
from @Table1 T
where not EXISTS
(select name from CTE
where name = T.Name )
结果:
NAME Score
Bill 1
Bill 2
Bill 1