COUNT MAX CASE 和 GROUP BY 用于重复类型 id

Posted

技术标签:

【中文标题】COUNT MAX CASE 和 GROUP BY 用于重复类型 id【英文标题】:COUNT MAX CASE and GROUP BY for recurring type id 【发布时间】:2019-06-26 22:13:24 【问题描述】:

我有这个观点,由多重连接产生:

project_id  | document_type_id
10          | 2
10          | 2
10          | 3
10          | 1
10          | 1
10          | 1
11          | 2
11          | 2
11          | 2
11          | 2
11          | 3
11          | 3

1 的标签:“评论”

2 的标签:“采访”

3 的标签:“浪漫”

这个表我已经拿到了:

project_id  | review     | interview | romance
10          | OK         | OK        | OK
11          | NO         | OK        | OK

使用以下查询语句:

SELECT `project_id`, `document_type_id`,
MAX(CASE WHEN `document_type_id` = 1 THEN "OK" ELSE "NO" END) as "review",
MAX(CASE WHEN `document_type_id` = 2 THEN "OK" ELSE "NO" END) as "interview",
MAX(CASE WHEN `document_type_id` = 3 THEN "OK" ELSE "NO" END) as "romance"

FROM projectDocumentList
GROUP BY project_id

我现在需要的是计算表格中每个字段中的每个文档类型:

project_id  | review | interview | romance
10          | 3      | 2         | 1
11          | 0      | 4         | 2

我试了又试,但我找不到正确的 sintax 来获得这个结果。 我之前的一些尝试...

COUNT(MAX(CASE WHEN `document_type_id` = 1 THEN "1" ELSE "NO" END)) as "review"

MAX(CASE WHEN `document_type_id` = 1 THEN (SELECT COUNT(`document_type_id`)) ELSE "NO" END) as "review"

COUNT(DISTINCT(MAX(CASE WHEN `document_type_id` = 1 THEN `document_type_id` ELSE "NO" END)) as "review"

【问题讨论】:

Count with if condition in mysql query的可能重复 你的主键是什么? 【参考方案1】:

你可以使用SUM()

查询

SELECT `project_id`,
SUM(CASE WHEN `document_type_id` = 1 THEN 1 ELSE 0 END) as "review",
SUM(CASE WHEN `document_type_id` = 2 THEN 1 ELSE 0 END) as "interview",
SUM(CASE WHEN `document_type_id` = 3 THEN 1 ELSE 0 END) as "romance"
FROM projectDocumentList
GROUP BY project_id

结果

| project_id | review | interview | romance |
| ---------- | ------ | --------- | ------- |
| 10         | 3      | 2         | 1       |
| 11         | 0      | 4         | 2       |

demo

也可以使用COUNT(..),但您需要使用NULL 而不是0。 这是因为COUNT(..) 处理0, 1 and NULL values 与SUM(..) 不同。

查询

SELECT `project_id`,
COUNT(CASE WHEN `document_type_id` = 1 THEN 1 ELSE NULL END) as "review",
COUNT(CASE WHEN `document_type_id` = 2 THEN 1 ELSE NULL END) as "interview",
COUNT(CASE WHEN `document_type_id` = 3 THEN 1 ELSE NULL END) as "romance"
FROM projectDocumentList
GROUP BY project_id

结果

| project_id | review | interview | romance |
| ---------- | ------ | --------- | ------- |
| 10         | 3      | 2         | 1       |
| 11         | 0      | 4         | 2       |

demo

【讨论】:

以上是关于COUNT MAX CASE 和 GROUP BY 用于重复类型 id的主要内容,如果未能解决你的问题,请参考以下文章

不能在 Group by/Order by/Where/ON 子句中使用 Group 或 Aggregate 函数(min()、max()、sum()、count()、...等)

GROUP BY + CASE 语句

min/max优化,count ,group by

带有表连接、case 语句、计数、group by 子句的 Linq 查询

如何使用 CASE 语句而不必将其放入 GROUP BY

group by...having count()的问题