2017-10-16 16 views
1

如何使用嵌套大小写并将结果分组在一起。 这里是我的查询:如何在SQL中使用嵌套大小写和组合结果

SELECT COUNT(inc.inc_id) AS event_count, 
CASE inc_data.event_type 
WHEN 'c' then case inc_data.sub_event_type 
       when 's' then 'SR' else 'Project' 
       end 
WHEN 'i' then 'incident' 
WHEN 'p' then 'Problem'  
WHEN 'd' then 'Decision' 
WHEN 't' then 'Task' 
end "event_sub_type" 
FROM inc INNER JOIN inc_data ON inc.inc_id = inc_data.inc_id  
GROUP BY inc_data.event_type, inc_data.sub_event_type 

返回:

+-------------+----------------+ 
| event_count | event_sub_type | 
+-------------+----------------+ 
|   5 | Project  | 
|   10 | Decision  | 
|   15 | Incident  | 
|   20 | Problem  | 
|   25 | Task   | 
|   30 | SR    | 
+-------------+----------------+ 

预期输出:

+-------------+----------------+ 
| event_count | event_sub_type | 
+-------------+----------------+ 
|   5 | Project  | 
|   25 | Others   | 
+-------------+----------------+ 

如何修改上面的查询,以获得预期的输出?

+0

你只是想筛选这两个记录? –

+0

是的,并将其他人合并在一起 –

+0

那么你在用什么? MySql或Sql Server?它们完全不一样,Sql Server也许可以通过MySql无法使用的窗口函数来解决这个问题。 –

回答

2

你可以试试吗?

SELECT COUNT(inc.inc_id) AS event_count, 
(CASE WHEN (inc_data.event_type = 'c' AND inc_data.sub_event_type <> 's') THEN 'Project' ELSE 'Others' END) "event_sub_type" 
      FROM inc INNER JOIN 
      inc_data ON inc.inc_id = inc_data.inc_id 
GROUP BY (CASE WHEN (inc_data.event_type = 'c' AND inc_data.sub_event_type <> 's') THEN 'Project' ELSE 'Others' END) 
0

如何

SELECT COUNT(inc.inc_id) AS event_count, 
    CASE inc_data.event_type 
    WHEN 'c' then case inc_data.sub_event_type 
       when 's' then 'Other' else 'Project' 
       end 
    ELSE 'Project' 
    END "event_sub_type" 
FROM inc INNER JOIN inc_data ON inc.inc_id = inc_data.inc_id  
GROUP BY inc_data.event_type, inc_data.sub_event_type 
-1

根据您的输出,我假设你正在使用MySQL。

MySQL允许您按列数,所以你可以用这个替换您的GROUP BY子句:

GROUP BY 1, 2 
+0

允许,是的。良好的做法?不经常。 –

相关问题