我想从歌曲作者中选择前3行而不使用top或max并过滤名称。
表:
CREATE TABLE Person (Name VARCHAR(10), song VARCHAR(10), length INT )
INSERT INTO Person
values
('Jim', 'songA', 8),
('Jim', 'songB', 5),
('Jim', 'songC', 7),
('Jim', 'songD', 4),
('Jimsky', 'songE', 8),
('Jim', 'songF', 6);
查询:
SELECT
p1.Name,
p1.song,
p1.length
FROM Person p1
WHERE EXISTS
(
SELECT *
FROM Person p2
WHERE p2.length < p1.length
AND p1.Name = 'Jim'
)
如何计算歌曲作者吉姆的前三行或前两行没有顶部/最大值?有计数?
由于
答案 0 :(得分:0)
我建议你:
SELECT
p1.Name,
p1.song,
p1.length
FROM Person p1
WHERE EXISTS
(
SELECT *
FROM Person p2
WHERE p2.length < p1.length
AND p1.Name = 'Jim'
)
ORDER BY <SomeRow> DESC LIMIT 3
但是我不了解你的背景,所以你能解释一下你将要实现的目标吗?
答案 1 :(得分:0)
您可以使用row_number()
执行此操作,假设您需要三首最长的歌曲:
select Name, song, length
from (select p.Name, p.song, p.length,
row_number() over (partition by p.name order by p.length desc) as seqnum
from person p
) p
where seqnum <= 3;