我有一个名为'PizzaData'的简单表,其中包含以下列:
cust_id INTEGER NOT NULL
bill_date INTEGER NOT NULL
pizza_amt INTEGER NOT NULL
bill_date
(为了简化练习)是自交易完成以来经过的天数。
我想提出的是以下报告:
+----------+-----------------+ | interval | total_pizza_amt | +----------+-----------------+ | 0-29 | X | | 30-59 | Y | | 60+ | Z | +----------+-----------------+
基本上我熟悉WITH
关键字但我刚刚意识到MySQL不支持它。所以我需要以某种方式生成临时列并将其与PizzaData
表连接。
如何用MySQL完成?
答案 0 :(得分:3)
我会把它写成:
select (case when bill_date < 30 then '0-29'
when bill_date < 60 then '30-59'
else '60+'
end) as bill_range,
sum(pizza_amt) as total_pizza_amt
from PizzaData
group by bill_range
order by min(bill_date);
注意:
case
表达式按顺序评估条件,因此您不需要between
。group by
子句中使用列别名(并非所有数据库都使用)。interval
是MySQL关键字和保留字。该列有更好的名称。order by
保证结果在&#34;逻辑&#34;顺序。答案 1 :(得分:2)
我觉得case
非常容易:
select case when bill_date <= 29 then '0-29'
when bill_date between 30 and 59 then '30-59'
else '60+' end `interval`,
sum(pizza_amt) `total_pizza_amt`
from PizzaData
group by case when bill_date <= 29 then '0-29'
when bill_date between 30 and 59 then '30-59'
else '60+' end;
或更清洁,使用子查询:
select `interval`, sum(pizza_amt) `total_pizza_amt` from (
select case when bill_date <= 29 then '0-29'
when bill_date between 30 and 59 then '30-59'
else '60+' end `interval`,
pizza_amt
from PizzaData
) `a` group by `interval`;