如何在数据库中将status列中的内容显示为标题

elcex8rz  于 2021-06-24  发布在  Mysql
关注(0)|答案(2)|浏览(272)

从mysql数据库中找到下面的数据,当我使用手机号码统计状态时,我需要将“status”显示为行的标题,“count”显示在状态的下面。


**cust_mob_no       status**

918072740683    unattended
918072740683    closed
918072740683    NotApplicable
918072740683    Assigned
918072740683    NotApplicable
918072740683    open
918072740683    open

帮助我使用mysql查询来显示如下所示的数据。。

unattended  closed  NotApplicable   Assigned    open
   1          1           2           1           2
swvgeqrz

swvgeqrz1#

这就是你需要的

SELECT
        cust_mob_no,  
        SUM(CASE WHEN (Status='unattended') THEN 1 ELSE 0 END) AS unattended,
        SUM(CASE WHEN (Status='closed' AND pagecount=1) THEN 1 ELSE 0 END) AS closed,
        SUM(CASE WHEN (Status='NotApplicable' AND pagecount=2) THEN 1 ELSE 0 END) AS NotApplicable,
        SUM(CASE WHEN (Status='Assigned' AND pagecount=3) THEN 1 ELSE 0 END) AS Assigned
    FROM 
        your_table
    GROUP BY 
        cust_mob_no
4dbbbstv

4dbbbstv2#

你可以这样使用select case

SELECT
    mobileNumber,  
    SUM(CASE WHEN (statusName='unattended') THEN 1 ELSE 0 END) AS unattended,
    SUM(CASE WHEN (statusName='closed' ) THEN 1 ELSE 0 END) AS closed,
    SUM(CASE WHEN (statusName='NotApplicable') THEN 1 ELSE 0 END) AS NotApplicable,
    SUM(CASE WHEN (statusName='Assigned') THEN 1 ELSE 0 END) AS Assigned
FROM 
    MyTable
GROUP BY 
    mobileNumber

dbfiddle示例代码
你可以利用pivot。示例查询

SELECT [unattended], [closed],[NotApplicable],[Assigned],[open] FROM   
(SELECT [mobileNumber],[status] FROM MyTable )Tab1  
PIVOT  
(  
COUNT([mobileNumber]) FOR status IN ([unattended], [closed],[NotApplicable], 
[Assigned],[open])) AS Tab2

db fiddle示例代码

相关问题