如何以更有效的方式重写此查询?

时间:2015-01-12 16:21:38

标签: sql

SELECT 'Application Developers' as team, COUNT(assignees) as tickets from TABLE20 where status <> 'Closed' AND assignees like '%Application Developers%' HAVING COUNT(assignees) <> 0  UNION ALL
SELECT 'Desktop Support' AS team, COUNT(assignees) AS tickets FROM TABLE20 WHERE status <> 'Closed' AND assignees LIKE '%Desktop Support%' HAVING COUNT(assignees) <> 0  UNION ALL
SELECT 'Enterprise Help Desk' AS team, COUNT(assignees) AS tickets FROM TABLE20 WHERE status <> 'Closed' AND assignees LIKE '%Enterprise Help Desk%' HAVING COUNT(assignees) <> 0  UNION ALL
SELECT 'Network Management' AS team, COUNT(assignees) AS tickets FROM TABLE20 WHERE status <> 'Closed' AND assignees LIKE '%Network Management%' HAVING COUNT(assignees) <> 0  UNION ALL
SELECT 'Query Writers' AS team, COUNT(assignees) AS tickets FROM TABLE20 WHERE status <> 'Closed' AND assignees LIKE '%Query Writers%' HAVING COUNT(assignees) <> 0  UNION ALL
SELECT 'Security' AS team, COUNT(assignees) AS tickets FROM TABLE20 WHERE status <> 'Closed' AND assignees LIKE '%Security%' HAVING COUNT(assignees) <> 0  UNION ALL
SELECT 'Server Admins' AS team, COUNT(assignees) AS tickets FROM TABLE20 WHERE status <> 'Closed' AND assignees LIKE '%Server Admins%' HAVING COUNT(assignees) <> 0  UNION ALL

ORDER BY tickets DESC

此查询产生以下结果:

team            tickets
Desktop Support 424
Enterprise Help Desk    96
Server Admins       46
Query Writers       15
Network Management  13
Application Developers  6
Security        6

如何重写此查询,使其看起来不像是一个全新的写入? =)

2 个答案:

答案 0 :(得分:2)

如果它是支持cte的数据库,您可以使用:

;WITH cte AS(SELECT CASE WHEN assignees like '%Application Developers%' THEN 'Application Developers' 
                        WHEN assignees LIKE '%Desktop Support%' THEN  'Desktop Support'
                        ....
                   END AS team
            FROM TABLE20 
            WHERE [status] <> 'Closed'
            )
SELECT team,COUNT(*) CT 
FROM  cte
GROUP BY team
HAVING COUNT(*) > 0

如果不是:

SELECT CASE WHEN assignees like '%Application Developers%' THEN 'Application Developers' 
            WHEN assignees LIKE '%Desktop Support%' THEN  'Desktop Support'
            ....
       END AS team
       ,COUNT(*) CT
FROM TABLE20 
WHERE [status] <> 'Closed'
GROUP BY CASE WHEN assignees like '%Application Developers%' THEN 'Application Developers' 
            WHEN assignees LIKE '%Desktop Support%' THEN  'Desktop Support'
            ....
         END
HAVING COUNT(*) > 0

GROUP BYSQL的基本元素,可以提供您所追求的功能。您可以一次性计算多个组中的所有元素,而不是单独计算元素组并组合结果。

答案 1 :(得分:0)

这会吗?

SELECT assignees, count(*) as tickets
FROM TABLE20
WHERE status <> 'Closed'
GROUP BY assignees
ORDER BY tickets DESC