mysql - 数据透视查询 - SUM() 的问题

标签 mysql sql pivot-table

我有以下查询:

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/

相关文章:

php - GLOBALS 参数的使用

javascript - 将 pivottablejs 图保存到文件

python pandas pivot_table 列一级错误名称

python - 将一列拆分为多列,计数频率: 'int' object is not iterable

mysql - MySQL中这个 "cursor"类型的查询如何解决?

mysql - 'sql_require_primary_key' - 在不创建主键的情况下无法将我的数据帧发送到 mysql 服务器

c# - 选择 Cast (Scope_identity) 并执行标量

mysql - 外键约束格式不正确[同表]

PHP 和 MySql 有日期问题...?

sql - MySQL索引构建性能