我需要做一个case语句,对结果进行分组并在SQL查询中计算结果。到目前为止,我已经做到了这一点,但不太确定如何让它正常工作:
SELECT 'OS' =
CASE
WHEN OS.Info LIKE 'AIX %' THEN 'Unix'
WHEN OS.Info LIKE 'LINUX%' THEN 'Unix'
END, COUNT( 'OS' )
FROM Asset A (NOLOCK)
LEFT JOIN Asset_IP AIP (NOLOCK) ON A.AssetID = AIP.AssetID AND AIP.LastUpdateDate = (SELECT MAX( Asset_IP.LastUpdateDate ) FROM Asset_IP (NOLOCK) WHERE A.AssetID = Asset_IP.AssetID)
LEFT JOIN Asset_IP_OS AIPOS (NOLOCK) ON AIP.AssetIPID = AIPOS.AssetIPID
LEFT JOIN OSNav OS (NOLOCK) ON AIPOS.OSNavID = OS.OSNavID
GROUP BY OS.Info
ORDER BY OS.Info
操作系统可能会出现在AIX 7.0或AIX 7.2或Linux 2.3或Windows 7或Solaris 10上。所有基于Unix的操作系统都必须在Unix下进行计数等...我希望它能显示这样的东西:
OS Count
Unix 200
Windows 1200
答案 0 :(得分:1)
您需要在CASE
中使用Group By
语句,或使用派生表来使用OS
中的别名group by
。由于我们已移除OS.Info
中的group by
,因此我们无法在OS.Info
中使用order by
。在OS
Order by
SELECT OS = CASE
WHEN OS.Info LIKE 'AIX %'
OR OS.Info LIKE 'LINUX%' THEN 'Unix'
ELSE 'Others' --default
END,
Count(OS.Info)
FROM Asset A (NOLOCK)
LEFT JOIN Asset_IP AIP (NOLOCK)
ON A.AssetID = AIP.AssetID
AND AIP.LastUpdateDate = (SELECT Max(Asset_IP.LastUpdateDate)
FROM Asset_IP (NOLOCK)
WHERE A.AssetID = Asset_IP.AssetID)
LEFT JOIN Asset_IP_OS AIPOS (NOLOCK)
ON AIP.AssetIPID = AIPOS.AssetIPID
LEFT JOIN OSNav OS (NOLOCK)
ON AIPOS.OSNavID = OS.OSNavID
GROUP BY CASE
WHEN OS.Info LIKE 'AIX %'
OR OS.Info LIKE 'LINUX%' THEN 'Unix'
ELSE 'Others'
END
ORDER BY OS
注意:我已添加else
语句,以便在表达式不满意时避免NULL's
。