SQLite数据库为here
我的问题是哪个国家的销售收入最高?每个国家占总收入的百分之几?
我已经解决了问题的第一部分。但是我不能解决第二个问题。
这是我的代码:
SELECT invoices.BillingCountry, SUM(invoice_items.UnitPrice * invoice_items.Quantity) Total
FROM invoices
JOIN invoice_items ON invoice_items.InvoiceId = invoices.InvoiceId
GROUP BY invoices.BillingCountry
ORDER BY SUM(invoice_items.UnitPrice * invoice_items.Quantity) DESC;
我该如何解决“每个国家占总收入的百分比?”
答案 0 :(得分:2)
您可以为此使用窗口功能:
SELECT
i.BillingCountry,
SUM(ii.UnitPrice * ii.Quantity) Total,
SUM(ii.UnitPrice * ii.Quantity) / SUM(SUM(ii.UnitPrice * ii.Quantity)) OVER() Ratio
FROM invoices i
JOIN invoice_items ii ON ii.InvoiceId = i.InvoiceId
GROUP BY i.BillingCountry
ORDER BY Total DESC;
sum()
窗口为您提供了整个数据集中每个国家/地区销售的sum()
。