如何对从mysql中的一列检索的结果进行分组

时间:2012-03-31 16:24:30

标签: mysql

我想做这样的事情:

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

1 个答案:

答案 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
;

(子查询实际上并不是必需的,但我认为它更清楚地发生了什么)。