我正在努力处理一个报告,我被要求使用SQL Server 2012进行编译。
报告需要包含一个月内在条形图中显示的机器数量。我们有3种不同的机器。我想写的查询应该显示机器B,Q,W以及为1月,2月等构建的那些机器的总数。
以下查询将机器分组为相关名称并给出计数(也仅包括所需机器的型号)
SELECT SUBSTRING(Name00, 1, 1) AS Workstations,
COUNT(*) AS Count,
Model00 AS "Machine Model"
FROM Computer_System_DATA
WHERE (Model00 LIKE N'HP Compaq Elite 8300 USDT')
GROUP BY SUBSTRING(Name00, 1, 1), Model00
HAVING (SUBSTRING(Name00, 1, 1) LIKE 'W%') OR
(SUBSTRING(Name00, 1, 1) LIKE 'B%') OR
(SUBSTRING(Name00, 1, 1) LIKE 'Q%') OR
(SUBSTRING(Name00, 1, 1) LIKE 'Y%') OR
(SUBSTRING(Name00, 1, 1) = 'AND HP Compaq Elite 8300 USDT')
我还有另一个使用同一个表的查询,并显示月份和当月内置的机器总数 -
SELECT CONVERT(Varchar(02), TimeKey, 101) AS Month,
COUNT(*) AS Total
FROM Computer_System_DATA
GROUP BY CONVERT(Varchar(02), TimeKey, 101)
ORDER BY Month
我的问题是,有没有办法将两个查询组合起来,以便为我提供每个月内构建的B,Q和W机器的总量。
如果不清楚或者我错过了什么,我道歉。如果有任何需要帮助,请告诉我。我是SQL和这个论坛的新手,我很难理解拥有多个组的概念。
非常感谢
答案 0 :(得分:1)
是。您还可以简化逻辑:
SELECT CONVERT(Varchar(02), TimeKey, 101) AS Month,
COUNT(*) AS Total
FROM Computer_System_DATA
WHERE Name00 like 'W%' OR
Name00 like 'B%' OR
Name00 like 'Q%'
GROUP BY CONVERT(Varchar(02), TimeKey, 101)
ORDER BY Month;
您无需使用like
和substring
进行比较。
分别获得总数:
SELECT CONVERT(Varchar(02), TimeKey, 101) AS Month,
COUNT(*) AS Total,
sum(case when Name00 like 'W%' then 1 else 0 end) as cnt_W,
sum(case when Name00 like 'B%' then 1 else 0 end) as cnt_B,
sum(case when Name00 like 'Q%' then 1 else 0 end) as cnt_Q
FROM Computer_System_DATA
WHERE Name00 like 'W%' OR
Name00 like 'B%' OR
Name00 like 'Q%'
GROUP BY CONVERT(Varchar(02), TimeKey, 101)
ORDER BY Month;