[https://www.sqlitetutorial.net/sqlite-sample-database/]
我编写此代码是为了获得“专辑“Big Ones”的总价是多少?”的答案
SELECT al.Title, i.Total, tr.albumid, SUM(tr.UnitPrice)
FROM ((((artists ar INNER JOIN albums al ON ar.ArtistId = al.ArtistId)
INNER JOIN tracks tr ON al.AlbumId = tr.AlbumId)
INNER JOIN invoice_items ii ON tr.TrackId = ii.TrackId)
INNER JOIN invoices i ON ii.invoiceid = i.invoiceid)
WHERE al.Title = 'Big Ones'
我得到
SUM(tr.UnitPrice)
为 9.9
。
但是9.9是错误的。正确答案应该是什么?
使用 Chinook 数据库中的表。上面提供了链接。
您必须将专辑所有曲目的单价相加,因此只需要 2 个表:
albums
和 tracks
。select a.title,
sum(t.unitprice) total_price
from albums a inner join tracks t
on t.albumid = a.albumid
where a.title = 'Big Ones'
group by a.title
即使省略
group by
子句,也可以获得相同的结果。
我选择了所有重要的键,然后连接两个表。您只需将“Big Ones”的单价相加即可
select al.albumid, sum(tr.unitprice), al.title
来自专辑
内连接轨道 tr on al.albumid = tr.albumid
where al.title =“大人物”
select
Title,
sum(UnitPrice)
from albums
join tracks
on albums.AlbumId = tracks.AlbumId
where albums.Title = 'Big Ones'