我正在创建一个查询来获取每季度的数据。
我在user_target
表quarter1
,quarter2
,quarter3
和quarter4
中有 4个字段
每个季度都有3个月,
quater1 - Jan Feb March
quater2 - Apr May June
quater3 - July Aug Sept
quater4 - Oct Nov Dec
现在当我在1月,2月或3月通过$ P {month}时,我应该得到quarter1的数据。同样地,当我在4月,5月或6月传递$ P {month}时,我应该获得quarter2等的数据。我不想在不同月份写出4个不同的查询。 可以在单个查询中实现吗?
我对quater1的查询如下:
select sum(t.quarter1) as quarter ,
s.name as sname, f.name as fname, m.name as pname
from user_target t, res_salesteam s,
account_fiscalyear f,res_users u, res_users ru, account_month m
where t.salesteam_id = s.id and
t.fiscal_year = f.id and
f.id = $P{fiscalyear} and
p.fiscalyear_id = f.id and
m.id = $P{month} and
u.parent_id = ru.id and
ru.id = $P{name} and (u.tri_salesteam = s.id or ru.tri_salesteam = u.id)
group by s.name, f.name, m.name order by s.name
答案 0 :(得分:3)
您可以使用CASE ... END逻辑构造
SELECT sum(CASE
WHEN $P{month} IN ('Jan','Feb','March') THEN t.quarter1
WHEN $P{month} IN ('Apr','May','June') THEN t.quarter2
WHEN $P{month} IN ('July','Aug','Sept') THEN t.quarter3
WHEN $P{month} IN ('Oct','Nov','Dec') THEN t.quarter4
ELSE 0 END) AS quarter,
s.name as sname, f.name as fname, m.name as pname
FROM ...
答案 1 :(得分:1)
使用MYSQL函数QUARTER()
获取四分之一的日期,并根据返回的季度使用sum
获得if /else
尝试以下:
select sum(if(QUARTER(start_date)=1,t.quarter1,0)) as quarter1,
SUM(if(QUARTER(start_date)=2,t.quarter2,0)) as quarter2,
SUM((QUARTER(start_date)=3,t.quarter3,0)) as quarter3,
SUM(IF(QUARTER(start_date)=4,quarter4,0)) as quarter4,s.name as sname, f.name as fname, m.name as pname
from user_target t, res_salesteam s, account_fiscalyear f,res_users u, res_users ru, account_month m
where t.salesteam_id = s.id and t.fiscal_year = f.id and f.id = $P{fiscalyear} and p.fiscalyear_id = f.id and m.id = $P{month}
and u.parent_id = ru.id and ru.id = $P{name} and (u.tri_salesteam = s.id or ru.tri_salesteam = u.id)
group by s.name, f.name, m.name order by s.name