在MySql中获取不同值的不同列的值计数

时间:2018-02-12 11:51:38

标签: php mysql

我在MySQL表格中有以下格式的数据。 我想在MySql查询中将字符串值的计数作为不同的列获取,这意味着如果列具有3个不同的值,则在从数据库获取数据时将向结果中添加3列。

表:

task table

id  | task      |
----|-----------|
1   | TASK1     |
----|-----------|
2   | TASK2     |
----|-----------|
3   | TASK3     |
----|-----------|

priority table

id  |  task_id  | priority  |
----|-----------|-----------|
1   |      1    |    Low    |
----|-----------|-----------|
2   |      1    |  Medium   |
----|-----------|-----------|
3   |      1    |   High    |
----|-----------|-----------|
4   |      1    |   High    |
----|-----------|-----------|
5   |      1    |   Low     |
----|-----------|-----------|
6   |      1    |   Medium  |
----|-----------|-----------|
7   |      1    |   High    |
 . 
 .
 N

预期结果:

task |low_priority  | medium_priority | high_priority
-----|--------------|-----------------|--------------
TASK1|    2         |        2        |      3    
-----|--------------|-----------------|--------------

现在,我正在尝试以下查询,但未找到预期的结果。

SELECT task, (CASE WHEN priority = 'low' THEN 1 ELSe 0 END ) AS 'low_priority',(CASE WHEN priority = 'medium' THEN 1 ELSE 0 END) AS 'medium_priority',(CASE WHEN priority = 'high' THEN 1 ELSE 0 END ) AS 'high_priority' FROM task LEFT JOIN priority ON priority.task_id = task.id GROUP BY task.id

1 个答案:

答案 0 :(得分:1)

你可以这样做

SELECT task, SUM(CASE WHEN priority = 'Low' THEN 1 ELSE 0 END )   AS 'low_priority',
             SUM(CASE WHEN priority = 'Medium' THEN 1 ELSE 0 END) AS 'medium_priority',
             SUM(CASE WHEN priority = 'High' THEN 1 ELSE 0 END )  AS 'high_priority'
FROM task 
LEFT JOIN priority ON priority.task_id = task.id GROUP BY task.id
HAVING SUM(CASE WHEN priority = 'Low' THEN 1 ELSE 0 END ) > 0    OR 
       SUM(CASE WHEN priority = 'Medium' THEN 1 ELSE 0 END ) > 0 OR
       SUM(CASE WHEN priority = 'High' THEN 1 ELSE 0 END )

,结果将是

+-------+--------------+-----------------+---------------+
| task  | low_priority | medium_priority | high_priority |
+-------+--------------+-----------------+---------------+
| TASK1 |            2 |               2 |             3 |
+-------+--------------+-----------------+---------------+
1 row in set (0.00 sec)