我有一张付款表:
worker_id, amount, payed, date
表工人:
id, name, lname
我需要编写一个SQL,它将为我,7月,8月,9月提供名称,名称和总和。
Name | Lname | Sum_JUN | Sum_JULY | Sum_AUG | Sum_SEP
我正在尝试子查询但不能这样做。你能救我吗?
我创建了SQL(示例)。我将用PHP替换日期。
select w.name, w.lname,
sum(case when p.payed_date between '2014-06-01' and '2014-06-31' then p.amount else 0 end) `sum_june`,
sum(case when p.payed_date between '2014-07-01' and '2014-07-31' then p.amount else 0 end) `sum_july`,
sum(case when p.payed_date between '2014-08-01' and '2014-08-31' then p.amount else 0 end) `sum_august`,
sum(case when p.payed_date between '2014-09-01' and '2014-09-31' then p.amount else 0 end) `sum_september`,
sum(case when p.payed_date between '2014-10-01' and '2014-10-31' then p.amount else 0 end) `sum_november`
from worker w
left join worker_sum p on(w.id = p.worker_id)
group by w.id
答案 0 :(得分:1)
您可以使用条件汇总作为您所需的金额,但这将为您提供表格中存在的所有年份的月份总和
select w.*,
sum(case when month(p.date) = 6 then p.amount else 0 end) `sum_june`,
sum(case when month(p.date) = 7 then p.amount else 0 end) `sum_july`,
sum(case when month(p.date) = 8 then p.amount else 0 end) `sum_august`,
sum(case when month(p.date) = 9 then p.amount else 0 end) `sum_september`
from workers w
left join payment p on(w.id = p.worker_id)
group by w.id