我有一个包含以下字段的订单表:id, name, price_paid
最简单的部分就是:
SELECT
name,
SUM(price_paid) AS total_price_paid
FROM
Orders GROUP BY
name
我应该如何修改我的SQL语句,以便在输出中获得以下内容?
name, total_price_paid, purchase_level
购买水平如下:
提前谢谢。
答案 0 :(得分:1)
使用条件总和:
SELECT
name,
SUM(IF(price_paid BETWEEN 0 AND 100, price_paid, 0)) AS sum_0_100,
SUM(IF(price_paid BETWEEN 101 AND 350, price_paid, 0)) AS sum_101_350,
SUM(IF(price_paid>350, price_paid, 0)) AS sum_350_plus
FROM
Orders
GROUP BY
name
或者,等级:
SELECT
name,
SUM(price_paid),
CASE
WHEN price_paid BETWEEN 0 AND 100 THEN 1
WHEN price_paid BETWEEN 101 AND 350 THEN 2
WHEN price_paid>350 THEN 3
END AS level
FROM
Orders
GROUP BY
name,
-- don't forget group then:
level
这两个查询之间的区别在于,fire会导致pivot,而second会导致普通行分组。
答案 1 :(得分:1)
SELECT
name,
SUM(price_paid) AS total_price_paid,
CASE WHEN SUM(price_paid) BETWEEN 0 AND 100 THEN 1
WHEN SUM(price_paid) BETWEEN 101 AND 350 THEN 2
WHEN SUM(price_paid) > 350 THEN 3 END AS purchase_level
FROM
Orders
GROUP BY
name