mysql - 有没有办法将单个字段值拆分为多列

标签 mysql sql database

我有一种情况,我应该显示 columnar 时尚

我正在使用这个查询

SELECT status, count(*) as total_
FROM companydata 
WHERE status = 'Not Emailed' or status = 'Not Emailed' or status = 'Email Sent' or status = 'Response Received' or status = 'Interested' or status =
'Not Interested'
GROUP BY status

它返回这样的东西

   status               total_
-|--------------------|--------------------------
    Not Emailed         9562
 |   Interested       |   2
    Response Received     45
 |  Email Sent        |   3000

有没有办法让它们看起来柱状时尚

Not Emailed    Interested    Response Received   Email Sent

9562             2               45                   3000

最佳答案

将您的原始查询更改为有条件地计数

SELECT Count(CASE WHEN status = 'Not Emailed' THEN 1 END) AS `Not Emailed`,
       Count(CASE WHEN status = 'Email Sent' THEN 1 END) AS `Email Sent`,
       Count(CASE WHEN status = 'Response Received' THEN 1 END) AS `Response Received`,
       Count(CASE WHEN status = 'Not Interested' THEN 1 END) AS `Not Interested`
FROM   yourtable
WHERE  status IN ( 'Not Emailed', 'Not Emailed', 'Response Received', 'Interested', 'Not Interested' ) 

或者,我们也可以使用 SUM 聚合来代替 COUNT

Sum(CASE WHEN status = 'Not Emailed' THEN 1 ELSE 0 END) AS `Not Emailed`

关于mysql - 有没有办法将单个字段值拆分为多列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41778300/

相关文章:

mysql - 如何使用 LOAD DATA INFILE 将 CSV 文件中的选定列插入 MySQL 数据库

mysql - 跨多个表搜索

php - 我想通过在 php 中使用 do--while 来执行一个 sql 更新循环语句

node.js - 多次测试运行后的 Sequelizejs/未知关系 "xxx"

javascript - 返回标准 SQL/BigQuery 结构并创建两列的 JS UDF

php - PDO prepare() 错误 Php/Mysql

sql - 如何创建数据成为列

结合两个非常快的查询时MySQL慢查询

sql - 选择仅属于特定部门的用户

c# - 如果创建出错,删除数据库