您好我渴望得到帮助,因为我在复杂的逻辑查询上被困了两天,如果有人可以帮忙解决的话。
订购表
id | region_id | created_at | sale
=============|=============|=========================
1 | 1 | 2011-09-21 | $250
2 | 2 | 2012-03-12 | $320
3 | 1 | 2010-09-15 | $300
4 | 2 | 2011-08-18 | $180
5 | 1 | 2012-04-13 | $130
6 | 3 | 2010-06-22 | $360
7 | 2 | 2011-09-25 | $330
区域表
id | region_name
=============|=============
1 | Region 1
2 | Region 2
3 | Region 3
预期输出
我试图实现的目标
select distinct `regions`.`region_name`, sum(orders.sale) as sum,
CASE WHEN MONTH(orders.created_at)>=4 THEN
concat(YEAR(orders.created_at), '-',YEAR(orders.created_at)+1)
ELSE concat(YEAR(orders.created_at)-1,'-', YEAR(orders.created_at))
END AS financial_year from `orders` inner join `regions` on `orders`.`region_id` = `regions`.`id` group by YEAR(orders.created_at), `regions`.`region_name` order by `orders`.`region_id` asc, YEAR(orders.created_at) asc
我的查询输出
在查询中我的逻辑问题在哪里,有一件事应该在财务年度明智地提取,而不仅仅是正常的年份。
由于
答案 0 :(得分:0)
http://sqlfiddle.com/#!9/16fdfb/9
只是为了修复您的查询,您不应该使用GROUP BY YEAR
,因为您的财政年度与日历年度不匹配,并且因为您不希望在不同的行但列中输出不同的财务年度。您可以将查询转换为:
SELECT regions.region_name,
o.salePrev as `2010-11`,
o.saleCurrent as `2011-12`
FROM (SELECT
region_id,
SUM(IF(MONTH(orders.created_at)<4,sale,0)) salePrev,
SUM(IF(MONTH(orders.created_at)>=4,sale,0)) saleCurrent
FROM orders
GROUP BY region_id
) o
INNER JOIN regions
ON o.region_id = regions.id;
但正如我在评论中提到的那样,你的条件MONTH(orders.created_at)<4
与年份无关,我会将其转换为:
SELECT regions.region_name,
o.salePrev as `2010-11`,
o.saleCurrent as `2011-12`
FROM (SELECT
region_id,
SUM(IF(
(MONTH(orders.created_at)<4 && YEAR(orders.created_at) = 2012)
|| YEAR(orders.created_at) < 2012
,sale,0)) salePrev,
SUM(IF(MONTH(orders.created_at)>=4 && YEAR(orders.created_at) = 2012,sale,0)) saleCurrent
FROM orders
GROUP BY region_id
) o
INNER JOIN regions
ON o.region_id = regions.id;
但是,它不是按年份分组,只是将当前(2012-04 +)年份与过去几年(2012-04 - )进行分组。
如果你需要所有年份......
更新 http://sqlfiddle.com/#!9/16fdfb/17
SELECT r.region_name,
SUM(IF(o.f_year=2010,o.y_sale,0)) as `2010-11`,
SUM(IF(o.f_year=2011,o.y_sale,0)) as `2011-12`,
SUM(IF(o.f_year=2012,o.y_sale,0)) as `2012-13`
FROM (SELECT
region_id,
IF(MONTH(orders.created_at)<4,YEAR(created_at)-1,YEAR(created_at)) f_year,
SUM(sale) y_sale
FROM orders
GROUP BY region_id, f_year
) o
INNER JOIN regions r
ON o.region_id = r.id
GROUP BY r.id