简体   繁体   English

如何计算 MySQL 中 pivot 表的值?

[英]How to count values ​on a pivot table in MySQL?

I have two tables Users and Get_cal like below:我有两个表UsersGet_cal ,如下所示:

Users用户

id_user(pk) id_user(pk) com com
1004 1004 700 700
1005 1005 700 700
1006 1006 700 700
1010 1010 701 701
1011 1011 701 701
1012 1012 701 701
1013 1013 701 701
1014 1014 800 800
1015 1015 800 800
1016 1016 800 800
1017 1017 800 800

Get_cal获取_cal

id_user(fk) id_user(fk) status地位
1004 1004 ABAN ABAN
1004 1004 ABAN ABAN
1004 1004 DES DES
1004 1004 LET
1004 1004 DES DES
1004 1004 ABAN ABAN
1011 1011 LET
1011 1011 LET
1011 1011 ABAN ABAN
1015 1015 ABAN ABAN
1015 1015 DES DES
1015 1015 LET
1015 1015 LET

For status column I have 5 types (ABAN,DES,LET,NOANS,OTH) .对于状态列,我有5 种类型 (ABAN,DES,LET,NOANS,OTH) I want to get this result like below( Get the count by user by status ):我想得到如下结果(按用户按状态获取计数):

id_user id_user ABAN ABAN DES DES LET NOANS诺安斯 OTH OTH
1004 1004 3 3个 2 2个 1 1个 0 0 0 0
1005 1005 0 0 0 0 0 0 0 0 0 0
1006 1006 0 0 0 0 0 0 0 0 0 0
1010 1010 0 0 0 0 0 0 0 0 0 0
1011 1011 1 1个 0 0 2 2个 0 0 0 0
1012 1012 0 0 0 0 0 0 0 0 0 0
1013 1013 0 0 0 0 0 0 0 0 0 0
1014 1014 0 0 0 0 0 0 0 0 0 0
1015 1015 1 1个 1 1个 2 2个 0 0 0 0
1016 1016 0 0 0 0 0 0 0 0 0 0
1017 1017 0 0 0 0 0 0 0 0 0 0

I have no idea how to start the query, please any suggestion?我不知道如何开始查询,请问有什么建议吗?

You want conditional aggregation here:您需要在此处进行条件聚合:

SELECT
    u.id_user,
    COUNT(CASE WHEN c.status = 'ABAN'  THEN 1 END) AS ABAN,
    COUNT(CASE WHEN c.status = 'DES'   THEN 1 END) AS DES,
    COUNT(CASE WHEN c.status = 'LET'   THEN 1 END) AS LET,
    COUNT(CASE WHEN c.status = 'NOANS' THEN 1 END) AS NOANS,
    COUNT(CASE WHEN c.status NOT IN ('ABAN', 'DES', 'LET', 'NOAN')
               THEN 1 END) AS OTH
FROM Users u
LEFT JOIN Get_cal c
    ON c.id_user = u.id_user
GROUP BY
    u.id_user
ORDER BY
    u.id_user;

If your status is always static with that 5 cases.如果您的状态始终为 static 且有 5 个案例。 you can use left join and group by and some switch case conditions to solve the query.您可以使用left joingroup by以及一些 switch case 条件来解决查询。

SELECT Users.id_user ,
SUM(CASE WHEN Get_cal.status = 'ABAN' THEN 1 ELSE 0 END) AS ABAN ,
SUM(CASE WHEN Get_cal.status = 'DES' THEN 1 ELSE 0 END) AS DES ,
SUM(CASE WHEN Get_cal.status = 'LET' THEN 1 ELSE 0 END) AS LET ,
SUM(CASE WHEN Get_cal.status = 'NOANS' THEN 1 ELSE 0 END) AS NOANS ,
SUM(CASE WHEN Get_cal.status = 'OTH' THEN 1 ELSE 0 END) AS OTH 
FROM Users LEFT JOIN Get_cal ON (Users.id_user = Get_cal.id_user) GROUP BY Users.id_user ,Get_cal.id_user

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM