如何计算 MySQL 中的累计和
How to calculate cumulative sums in MySQL
我正在准备面试,在练习最近在亚马逊上提出的一些 SQL 问题时遇到了这个问题。虽然我找不到 table,但问题如下:
查找过去 6 个月西雅图客户的前 10 大最有利table 产品的累计总和。
解决此类查询的方法看起来正确吗?如果没有,解决这个问题的最佳方法是什么?
SELECT t.day,
t.product_count,
@running_total:=@running_total + t.product_count AS cumulative_sum
FROM
( SELECT
date(purchase_date) as day,
count(product_id) as product_count
FROM products
where day > DATE_SUB(now(), INTERVAL 6 MONTH)
AND customer_city = 'Seattle'
GROUP BY day
ORDER BY product_count desc) t
JOIN (SELECT @running_total:=0) r
ORDER BY t.day
LIMIT 10;
使用这个
select day,product_count,
sum(product_count) over (order by t.day ROWS UNBOUNDED PRECEDING) as cumulative_sum from (
SELECT
date(purchase_date) as day,
count(product_id) as product_count
FROM products
where day > DATE_SUB(now(), INTERVAL 6 MONTH)
AND customer_city = 'Seattle'
GROUP BY day
ORDER BY product_count desc
)t
我正在准备面试,在练习最近在亚马逊上提出的一些 SQL 问题时遇到了这个问题。虽然我找不到 table,但问题如下:
查找过去 6 个月西雅图客户的前 10 大最有利table 产品的累计总和。
解决此类查询的方法看起来正确吗?如果没有,解决这个问题的最佳方法是什么?
SELECT t.day,
t.product_count,
@running_total:=@running_total + t.product_count AS cumulative_sum
FROM
( SELECT
date(purchase_date) as day,
count(product_id) as product_count
FROM products
where day > DATE_SUB(now(), INTERVAL 6 MONTH)
AND customer_city = 'Seattle'
GROUP BY day
ORDER BY product_count desc) t
JOIN (SELECT @running_total:=0) r
ORDER BY t.day
LIMIT 10;
使用这个
select day,product_count,
sum(product_count) over (order by t.day ROWS UNBOUNDED PRECEDING) as cumulative_sum from (
SELECT
date(purchase_date) as day,
count(product_id) as product_count
FROM products
where day > DATE_SUB(now(), INTERVAL 6 MONTH)
AND customer_city = 'Seattle'
GROUP BY day
ORDER BY product_count desc
)t