SQL计数名称和操作系统

时间:2016-02-10 19:51:04

标签: sql count

我有一个看起来像这样的表:

PC-Name     OperatingSystem
-------     ---------------
Dep01-pc1   Win7
Dep01-pc2   WinXP
Dep02-pc1   Win7
Dep02-pc2   Win7

我想查询会产生这样的结果:

Department    PC-Count  Win7-Count    WinXP-Count
----------    --------  ----------    -----------
Dep01         2         1             1
Dep02         2         2             0

在单个查询中甚至可以做到吗?

我尝试了以下操作并且无效:

SELECT
    (SELECT COUNT() FROM table WHERE department LIKE '%01'),
    (SELECT COUNT() FROM table WHERE department LIKE '%01' and OS like 'Win7')

谢谢!

1 个答案:

答案 0 :(得分:0)

有点难看,但这就是诀窍:

SELECT Department
    ,COUNT(*) AS 'Department Count'
    ,SUM(CASE 
            WHEN OS LIKE 'Win7%'
                THEN 1
            ELSE 0
            END) AS '7 Count'
    ,SUM(CASE 
            WHEN OS LIKE 'WinXP%'
                THEN 1
            ELSE 0
            END) AS 'XP Count'
FROM (
    SELECT LEFT([PC-Name], CHARINDEX('-', [PC-Name]) - 1) AS 'Department'
        ,SUBSTRING([PC-Name], CHARINDEX('-', [PC-Name], 1) + 1, LEN([PC-Name]) - CHARINDEX('-', [PC-Name], 1)) AS 'Name'
        ,OS
    FROM machines
    ) x
GROUP BY Department

image