我应该写一个查询来查找“查找总销售额最高的艺术家的名字”。 我写的查询就是这个:
SELECT Ar.Name, SUM(IL.UnitPrice) AS ts
FROM Artist Ar
JOIN Album Al ON Ar.ArtistId=Al.ArtistId
JOIN Track Tr ON Al.AlbumId=Tr.AlbumId
JOIN InvoiceLine IL ON IL.TrackId=Tr.TrackId
JOIN Invoice I ON I.InvoiceId=IL.InvoiceId
GROUP BY Ar.Name
HAVING ts >= ALL (SELECT SUM(IL.UnitPrice) AS ts
FROM Artist Ar
JOIN Album Al ON Ar.ArtistId=Al.ArtistId
JOIN Track Tr ON Al.AlbumId=Tr.AlbumId
JOIN InvoiceLine IL ON IL.TrackId=Tr.TrackId
JOIN Invoice I ON I.InvoiceId=IL.InvoiceId
GROUP BY Ar.Name)
我正在使用DB Browser for SQLite,当我运行查询时,它显示near "ALL" syntax error:
此查询应适用于Chinook数据库,架构位于this link
谢谢。
答案 0 :(得分:1)
您可以使用order by
和limit
。当没有最高销售额的关系时,这将起作用。
SELECT Ar.Name, SUM(IL.UnitPrice) AS ts
FROM Artist Ar
JOIN Album Al ON Ar.ArtistId=Al.ArtistId
JOIN Track Tr ON Al.AlbumId=Tr.AlbumId
JOIN InvoiceLine IL ON IL.TrackId=Tr.TrackId
JOIN Invoice I ON I.InvoiceId=IL.InvoiceId
GROUP BY Ar.Name
ORDER BY ts DESC LIMIT 1
编辑:在发生关系时获得所有最大销售额。
select t1.name from
(SELECT Ar.Name, SUM(IL.UnitPrice) AS ts
FROM Artist Ar
JOIN Album Al ON Ar.ArtistId=Al.ArtistId
JOIN Track Tr ON Al.AlbumId=Tr.AlbumId
JOIN InvoiceLine IL ON IL.TrackId=Tr.TrackId
JOIN Invoice I ON I.InvoiceId=IL.InvoiceId
GROUP BY Ar.Name) t1
JOIN (select max(ts) as maxsale from
(SELECT Ar.Name, SUM(IL.UnitPrice) AS ts
FROM Artist Ar
JOIN Album Al ON Ar.ArtistId=Al.ArtistId
JOIN Track Tr ON Al.AlbumId=Tr.AlbumId
JOIN InvoiceLine IL ON IL.TrackId=Tr.TrackId
JOIN Invoice I ON I.InvoiceId=IL.InvoiceId
GROUP BY Ar.Name) t) totals
ON totals.maxsale = t1.ts