我有以下查询:
SELECT asunto, MONTH(created_at) as mes, COUNT(turno) as numero
FROM tikets
where id_sucursal = 1 and subasunto = 'Pago' GROUP BY asunto, mes ORDER BY mes ASC
这给了我这样的结果:
我想知道如何进行咨询以使其发挥作用或我将要做的事情。谢谢你的关注
答案 0 :(得分:1)
使用条件聚合:
SELECT t.asunto,
SUM(MONTH(t.created_at) = 2) as month_2,
SUM(MONTH(t.created_at) = 3) as month_3,
SUM(MONTH(t.created_at) = 4) as month_4,
SUM(MONTH(t.created_at) = 5) as month_5
FROM tikets t
WHERE t.id_sucursal = 1 AND t.subasunto = 'Pago'
GROUP BY asunto;
一个警告:在工作几个月时,您通常需要考虑这一年。
答案 1 :(得分:0)
MySQL没有PIVOT
函数来执行此类操作,但是,您可以执行以下操作:
SELECT t.asunto,
(SELECT COUNT(turno) FROM tikets WHERE MONTH(created_at) = 2 AND asunto = t.asunto AND id_sucursal = 1 and subasunto = 'Pago') as '2',
(SELECT COUNT(turno) FROM tikets WHERE MONTH(created_at) = 3 AND asunto = t.asunto AND id_sucursal = 1 and subasunto = 'Pago') as '3',
(SELECT COUNT(turno) FROM tikets WHERE MONTH(created_at) = 4 AND asunto = t.asunto AND id_sucursal = 1 and subasunto = 'Pago') as '4',
(SELECT COUNT(turno) FROM tikets WHERE MONTH(created_at) = 5 AND asunto = t.asunto AND id_sucursal = 1 and subasunto = 'Pago') as '5'
FROM tikets t
where t.id_sucursal = 1 and t.subasunto = 'Pago'
GROUP BY asunto