我有这样的观点,这是由于多重联接造成的:
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
我尝试了很多次,但是我找不到正确的正税来获得此结果。 我以前的一些尝试...
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"
有关任何想法? 谢谢。 V。
答案 0 :(得分: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 |
也可以使用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 |