我有以下查询:
select
extract(year from p.when_paid) yyyy,
MONTHNAME(STR_TO_DATE(extract(month from p.when_paid), '%m')) mm,
f.name,
IF(p.payment_type_id = 1,SUM(p.amount),null) MedPay,
IF(p.payment_type_id = 2,SUM(p.amount),null) Liability,
IF(p.payment_type_id = 3,SUM(p.amount),null) WC,
IF(p.payment_type_id in (8,9),SUM(p.amount),null) VA,
IF(p.payment_type_id = 10,SUM(p.amount),null) Health
from services s
join payments p on p.service_id = s.id
join accounts a on a.id = s.account_id
join facilities f on f.id = a.facility_id
GROUP BY f.name, yyyy, mm
ORDER BY f.name ASC;
现在我可以获取要填充的表,但它不按 payment_type 排序。例如,它将汇总 MedPay 或 Liability 中的所有付款,但不会像数据透视表那样拆分它们。最好的方法是什么?这是表结构:
amount when_paid payment_type_id
---------------------------------------
500 2013-02-02 2
400 2013-02-02 3
250 2013-02-02 2
我希望输出看起来像
yy mm name MedPay Liability WC VA Health
----------------------------------------------------
2013 2 Fact 750 400
最佳答案
IF(p.payment_type_id = 1,SUM(p.amount),null)
-->
SUM(IF(p.payment_type_id = 1, p.amount, 0))
或者您可以将 0
更改为 NULL
。我认为这将以空白而不是 0 作为值结束(当表中没有条目具有 type_id=1
时)。
或者,要显示“无”:
IFNULL(SUM(IF(p.payment_type_id = 1, p.amount, NULL)), 'none')
关于mysql - 数据透视查询 - SUM() 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35246988/