这是表Schema:
CREATE TABLE `profit_log` (
`market_id` smallint(6) NOT NULL,
`total_purchase` bigint(20) NOT NULL,
`total_profit` bigint(20) NOT NULL,
`company_profit` bigint(20) NOT NULL,
`date` date NOT NULL,
`tid` bigint(20) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci;
--
-- Indexes for table `profit_log`
--
ALTER TABLE `profit_log`
ADD PRIMARY KEY (`tid`);
我正在使用以下查询计算日期之间的累积购买:
SELECT `market_id`,
SUM(`total_purchase`) as acc_purchase,
SUM(`total_profit`) as acc_profit,
SUM(`company_profit`) as acc_company_profit
FROM `profit_log`
WHERE `date` >= '2016-01-01'
AND `date` < ('2016-01-20' + INTERVAL 1 DAY)
AND `market_id` IN (1,2,5,8,22)
GROUP BY `market_id`
我想知道是否可以计算此查询中每个market_id
的增长率?
growth rate = ((total_purchase as top where date = '2016-01-20')-(total_purchase as bottom where date = '2016-01-01')/bottom) * 100
是否可以在一个查询中完成所有操作,或者需要在单独的查询中进行计算?
感谢。
答案 0 :(得分:0)
试试这个:
SELECT o.`market_id`,
SUM(o.`total_purchase`) as acc_purchase,
SUM(o.`total_profit`) as acc_profit,
SUM(o.`company_profit`) as acc_company_profit,
(SELECT total_purchase FROM profit_log as i WHERE o.market_id = i.market_id AND i.`date` = '2016-01-01')
/
(SELECT total_purchase FROM profit_log as i WHERE o.market_id = i.market_id AND i.`date` = '2016-01-20')
as growth_rate,
FROM `profit_log` as o
WHERE `date` >= '2016-01-01'
AND `date` < ('2016-01-20' + INTERVAL 1 DAY)
AND `market_id` IN (1,2,5,8,22)
GROUP BY `market_id`