使用case / if在Mysql中获取特定计数

时间:2015-07-20 19:00:56

标签: mysql

我正在尝试为我的销售代理商制定一个激励计划,具体取决于订单数量以及他们的工作转移。

sales表(mysql)包含以下列:

sale_id (int, primary, auto increment)
employee (varchar, 255)
sale_time (datetime, the time sale was placed)
sale_amount (float 10,2)
sales_channel (tinyint, with values call (1), walk_in (2),referral(3))
is_cancelled (tinyint, with values 1 for cancelled, and 0 as default)
(and a few other columns that are not relevant for this case)

我想写一个查询来获取带有以下列的结果(我可以互换地使用订单和销售):

employee
total_orders (count excluding cancelled sales, i.e. is_cancelled!= 1)
orders_below_100dollars (orders count with sale_amount below 100 and is_cancelled = 0)
orders_above_100dollars (orders count with sale_amount above 100 and is_cancelled = 0)
orders_dayShift (orders count placed between 9am and before 10pm and is_cancelled = 0)
orders_nightShift (orders count placed after 10pm and before next day 9am and is_cancelled = 0)
cancelled_orders (orders count with is_cancelled = 1)

我知道查询在选择中会有group bycaseif/else,但无法正确构建。请帮忙。

2 个答案:

答案 0 :(得分:3)

您希望使用条件聚合 - 以下是几个示例:

select employee, 
       sum(case when is_cancelled != 1 then 1 else 0 end) total_orders,
       sum(case when sale_amount < 100 then 1 else 0 end) orders_below_100dollars,
       sum(case when sale_amount >= 100 then 1 else 0 end) orders_above_100dollars,
       ...
from sales
group by employee

我不确定白天与夜间的构成是什么,但鉴于上述情况,应该很容易添加。

答案 1 :(得分:2)

您可以对很多这些使用条件聚合。换句话说,将条件置于SUM()函数内以获取符合特定条件的行数:

SELECT employee, 
   SUM(is_cancelled <> 1) AS totalOrders, 
   SUM(sale_amount < 100 AND is_cancelled <> 1) AS orders_below_100,
   SUM(sale_amount > 10 AND is_cancelled <> 1) AS orders_above_100,
   SUM(sale_time < '22:00:00' AND is_cancelled <> 1) AS orders_dayshift,
   SUM(sale_time > '22:00:00' AND is_cancelled <> 1) AS orders_nightshift,
   SUM(is_cancelled = 1) AS totalCanceled
FROM sales
GROUP BY employee;