表有销售额,我正在尝试计算销售额和总销售额百分比。
WITH t1 AS (
SELECT
product_id,
sum(financial_charge_cents) as cents
FROM "account_charges"
WHERE account_id = 5
AND status = 'Charged'
GROUP BY product_id
ORDER BY cents DESC
)
SELECT
product_id,
cast(cents as money) / 100.0 AS dollars,
cents / (sum(cents) OVER (PARTITION BY product_id)) as percent
FROM t1
ORDER BY dollars DESC
但这会使所有百分比返回1
而不确定原因。
不确定这是类型问题还是什么问题。
答案 0 :(得分:1)
OVER (PARTITION BY produuct_id)
导致总和与cents
相同。您不需要分区:
SELECT
product_id,
cast(cents as money) / 100.0 AS dollars,
cents* 1.0 / (sum(cents) OVER ()) as percent
FROM t1
ORDER BY dollars DESC
注意,我添加了*1.0
来获取数字结果。如果cents
是数字(非整数),则跳过它。