使用Chinook Test Database我写了这个SQL语句来显示两个特定客户订购的所有曲目:
SELECT inv.BillingCity,cus.LastName,tra.Name
FROM invoice AS inv
JOIN customer AS cus ON inv.CustomerId=cus.CustomerId
JOIN invoiceline inl ON inv.InvoiceId=inl.InvoiceId
JOIN track tra ON tra.TrackId=inl.TrackId
WHERE cus.LastName IN ('Schneider','Schröder')
ORDER BY inv.BillingCity,cus.LastName,tra.Name
我发现有一个客户订购了两次跟踪:
我如何编写SQL语句来查找这样的双打,即“返回一位客户多次订购的所有曲目”?
答案 0 :(得分:2)
试试这个:
SELECT cus.CustomerId,tra.Name,COUNT(cus.CustomerId) AS tot
FROM invoice AS inv
JOIN customer AS cus ON inv.CustomerId=cus.CustomerId
JOIN invoiceline inl ON inv.InvoiceId=inl.InvoiceId
JOIN track tra ON tra.TrackId=inl.TrackId
GROUP BY cus.CustomerId,tra.Name
HAVING tot > 1