如何从表格中的字段中获取每月记录的总金额。
我有2个表,客户和活动,活动中有成本(双)字段和外键客户ID,想要显示客户以及给定日期的成本总和。
我在查询时将日期为2016-01的成本值相加,在这种情况下,我希望每月,1月,2月,3月展示....
select idcliente,
nombre,
sum(costo) as costo
from actividad
inner join cliente
on actividad.cliente_idcliente = cliente.idcliente
where cliente_idcliente = 82
group by fecha=2016-01;
并且此咨询适用于我的所有客户,而不仅仅是一个
示例:我想要显示一个像http://imgur.com/a/6jYlB
这样的表格答案 0 :(得分:3)
使用月份功能
select
YEAR(fecha) as Anno
MONTH(fecha) as Mes,
min(idcliente),
min(nombre),
sum(costo) as costo
from actividad
inner join cliente on actividad.cliente_idcliente=cliente.idcliente
where cliente_idcliente=82
group by year(fecha), month(fecha)
答案 1 :(得分:2)
看起来您需要一个数据透视查询结果,一年中有12个月是列,每条记录对应一个给定的客户。请尝试以下查询:
SELECT idcliente,
SUM(CASE WHEN MONTH(fecha) = 1 THEN costo ELSE 0 END) AS January,
SUM(CASE WHEN MONTH(fecha) = 2 THEN costo ELSE 0 END) AS February,
SUM(CASE WHEN MONTH(fecha) = 3 THEN costo ELSE 0 END) AS March,
SUM(CASE WHEN MONTH(fecha) = 4 THEN costo ELSE 0 END) AS April,
SUM(CASE WHEN MONTH(fecha) = 5 THEN costo ELSE 0 END) AS May,
SUM(CASE WHEN MONTH(fecha) = 6 THEN costo ELSE 0 END) AS June,
SUM(CASE WHEN MONTH(fecha) = 7 THEN costo ELSE 0 END) AS July,
SUM(CASE WHEN MONTH(fecha) = 8 THEN costo ELSE 0 END) AS August,
SUM(CASE WHEN MONTH(fecha) = 9 THEN costo ELSE 0 END) AS September,
SUM(CASE WHEN MONTH(fecha) = 10 THEN costo ELSE 0 END) AS October,
SUM(CASE WHEN MONTH(fecha) = 11 THEN costo ELSE 0 END) AS November,
SUM(CASE WHEN MONTH(fecha) = 12 THEN costo ELSE 0 END) AS December
FROM actividad
INNER JOIN cliente
ON actividad.cliente_idcliente = cliente.idcliente
WHERE cliente_idcliente = 82 AND -- remove this to see monthly summary for all customers
YEAR(fecha) = 2016 -- change this to whatever year you want to see
GROUP BY idcliente