我想做这样的事情:
SELECT sum(quantity)
FROM orders
WHERE order_code between **code1** and **code2** as group1
and order_code between **code3** and **code4** as group2
and order_code between **code5** and **code6** as group3
答案 0 :(得分:1)
如果您想要一行包含三列:
SELECT SUM(IF(order_code BETWEEN ... AND ..., quantity, 0)), -- group1
SUM(IF(order_code BETWEEN ... AND ..., quantity, 0)), -- group2
SUM(IF(order_code BETWEEN ... AND ..., quantity, 0)) -- group3
FROM orders
;
如果您想要一个包含三行的列:
SELECT group_number,
SUM(quantity)
FROM ( SELECT quantity,
CASE WHEN order_code BETWEEN ... AND ... THEN 1 -- group1
WHEN order_code BETWEEN ... AND ... THEN 2 -- group2
WHEN order_code BETWEEN ... AND ... THEN 3 -- group3
ELSE NULL
END AS group_number
FROM orders
) AS t
WHERE group_number IS NOT NULL
GROUP
BY group_number
;
(子查询实际上并不是必需的,但我认为它更清楚地发生了什么)。