我剛剛開始熟悉SQL,我發現語言很簡單,但也有時非常混亂。例如藉此聲明SQL百分比優雅
SELECT transaction.ID,
dt,
bundles.package_name as "Package Name",
amount_usd,
unit_sales,
CASE
WHEN sum(amount_usd) = 0 THEN 0
ELSE round(amount_usd*100/ (SELECT sum(amount_usd) FROM transaction
WHERE (transaction.code = 'AA')
AND (transaction.country_code = 'US')
AND (dt BETWEEN '2016-01-01' and '2016-01-04')),2)
END as percentage
FROM transaction
JOIN bundles
ON transaction.package_id= cast(bundles.id as INT)
WHERE (transaction.code = 'AA')
AND (transaction.country_code = 'US')
AND (dt BETWEEN '2016-01-01' and '2016-01-04')
GROUP BY transaction.ID, dt, "Package Name"
ORDER BY transaction.ID
limit 1000
我發現浪費一點點不得不重複SELECT加上只是正確計算的百分比。有沒有更優雅的解決方案來避免這種情況?
下面是我如何修復它。
如果你想在總量的百分數,你不一定需要嵌套
SELECT t.ID, dt, b.package_name as "Package Name",
SUM(amount_usd) as amount_usd, SUM(unit_sales) as unit_sales,
SUM(amount_usd) * 1.0/SUM(amount_usd) OVER() as ratio
FROM transaction t JOIN
bundles b
ON t.package_id = cast(b.id as INT)
WHERE (t.code = 'AA') AND
(t.country_code = 'US') AND
(dt BETWEEN '2016-01-01' and '2016-01-04')
GROUP BY t.ID, dt, "Package Name"
ORDER BY t.ID
LIMIT 1000;
如果你想收入超過每天總的比你做
SELECT t.ID, dt, b.package_name as "Package Name",
SUM(amount_usd) as amount_usd, SUM(unit_sales) as unit_sales,
SUM(amount_usd) * 1.0/SUM(amount_usd) OVER (PARTITION BY dt) as ratio
FROM transaction t JOIN
bundles b
ON t.package_id = cast(b.id as INT)
WHERE (t.code = 'AA') AND
(t.country_code = 'US') AND
(dt BETWEEN '2016-01-01' and '2016-01-04')
GROUP BY t.ID, dt, "Package Name"
ORDER BY t.ID
LIMIT 1000;
用你正在使用的數據庫標記你的問題。 –
@GordonLinoff added –