MySQL实现行转列方式一

MySQL数据库中有很多方式实现行转列,在面试中也是经常考的SQL语句。

这个问题的本质其实就是如何实现行转列(How to count values ​on a pivot table in MySQL)。

原问题:

I have two tables Users and Get_cal like below :

id_user(pk)com
1004700
1005700
1006700
1010701
1011701
1012701
1013701
1014800
1015800
1016800
1017800
Users

id_user(fk)status
1004ABAN
1004ABAN
1004DES
1004LET
1004DES
1004ABAN
1011LET
1011LET
1011ABAN
1015ABAN
1015DES
1015LET
1015LET
Get_cal

For status column I have 5 types (ABAN,DES,LET,NOANS,OTH). I want to get this result like below(Get the count by user by status ):

d_userABANDESLETNOANSOTH
100432100
100500000
100600000
101000000
101110200
101200000
101300000
101400000
101511200
101600000
101700000
Result

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;

问题解析

该问题主要目的就是想将结果行显示为列也就是行转列,通过case when的方式实现也是最简单的。这里面因为明确status只有五种,所以最后一种status才通过排除其他status的方式进行展示,其实直接写OTH反而比较好,因为不是每个用户都有相关状态所以需要使用Left join。具体运行结果可以查看 dbfiddle

本文根据StackOverflow翻译而来,不代表烟海拾贝立场,如若转载,请注明出处:https://somirror.com/554.html

(0)
上一篇 2022-02-17 22:03
下一篇 2022-02-18 22:17

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注