我目前正在尝试自学SQL,以便使用我们的Orion系统编写更好的报告,并且我遇到了一个小问题。我想生成一个包含Windows机器和Linux机器数量的报告。这是我目前的代码。
SELECT OperatingSystem, Count(OperatingSystem) AS TotalMachines
FROM Machines
Where
(
(OperatingSystem LIKE '%Windows%') OR
(OperatingSystem LIKE '%Linux%')
)
GROUP BY OperatingSystem
我得到的回报就是这个
Red Hat Enterprise Linux 20
Novell SUSE Linux Enterprise 17
Debian Linux 5
Windows Server 2008 (32-bit) 11
Windows Server 2008 R2 (32-bit) 49
Windows Server 2008 (64-bit) 33
Windows Server 2008 R2 (64-bits) 16
Windows Server 2003 (32-bit) 35
是否可以将所有不同的Linux操作系统组合成一个名为Linux的行,并将所有Windows操作系统组合成一个名为Windows的SQL查询行?
答案 0 :(得分:3)
是。您想在case
子句中使用group by
:
SELECT (case when OperatingSystem LIKE '%Windows%' then 'Windows'
when OperatingSystem LIKE '%Linux%' then 'Linux'
end) as WhichOs, Count(*) AS TotalMachines
FROM Machines
Where (OperatingSystem LIKE '%Windows%') OR
(OperatingSystem LIKE '%Linux%')
GROUP BY (case when OperatingSystem LIKE '%Windows%' then 'Windows'
when OperatingSystem LIKE '%Linux%' then 'Linux
end);
编辑:
以上内容应该有效(请注意select
和group by
中的相同表达式。也许这样可行:
SELECT WhichOs, Count(*) AS TotalMachines
FROM (SELECT m.*,
(case when OperatingSystem LIKE '%Windows%' then 'Windows'
when OperatingSystem LIKE '%Linux%' then 'Linux'
end) as WhichOs
FROM Machines m
) m
Where (OperatingSystem LIKE '%Windows%') OR
(OperatingSystem LIKE '%Linux%')
GROUP BY WhichOs;
答案 1 :(得分:0)
尝试这样的事情:
SELECT
case
when OperatingSystem like '%Windows%' then 'Windows'
when OperatingSystem like '%Linux%' then 'Linux'
else 'Other'
end as Operating_System
, Count(OperatingSystem) AS TotalMachines
FROM Machines
Where
(
(OperatingSystem LIKE '%Windows%') OR
(OperatingSystem LIKE '%Linux%')
)
GROUP BY
OperatingSystem
, case
when OperatingSystem like '%Windows%' then 'Windows'
when OperatingSystem like '%Linux%' then 'Linux'
else 'Other'
end
答案 2 :(得分:0)
要解决此类问题,我更倾向于使用union
case
,因为它可以帮助您以后轻松扩展查询:
select OSType, count(*) as TotalMachines
from (
SELECT 'Linux' as OSType FROM Machines WHERE OperatingSystem LIKE '%Linux%'
UNION ALL
SELECT 'Windows' as OSType FROM Machines WHERE OperatingSystem LIKE '%Windows%'
) as subquery
GROUP BY OSType
无论如何,请检查两种变体并选择最快的