如何在查询中将行组合在一起?

时间:2013-06-04 16:21:37

标签: sql sql-server sql-server-2008 tsql

我试图通过查看操作系统来区分物理服务器的正常运行时间。我能够得出VMWare操作系统的结果,但是,我想将物理服务器分组为一行。

这是我到目前为止的代码:

   SELECT TOP (100) PERCENT Avg(dbo.tblserveruptime.uptime) AS Uptime, 
                         Count(*)                        AS Total 
FROM   dbo.server 
       INNER JOIN dbo.tblserveruptime 
               ON dbo.server.name = dbo.tblserveruptime.name 
WHERE  ( dbo.server.status = N'production' ) 
       AND ( dbo.server.server_env = N'prod' ) 
       AND ( dbo.server.os_type <> N'vmware' ) 
GROUP  BY dbo.tblserveruptime.month, 
          dbo.tblserveruptime.year 
HAVING ( dbo.tblserveruptime.month = 4 ) 
       AND ( dbo.tblserveruptime.year = 2013 ) 
UNION 
SELECT TOP (100) PERCENT Avg(dbo.tblserveruptime.uptime) AS Uptime, 
                         Count(*)                        AS Total 
FROM   dbo.server 
       INNER JOIN dbo.tblserveruptime 
               ON dbo.server.name = dbo.tblserveruptime.name 
WHERE  ( dbo.server.status = N'production' ) 
       AND ( dbo.server.server_env = N'prod' ) 
       AND ( dbo.server.os_type = N'vmware' ) 
GROUP  BY dbo.tblserveruptime.month, 
          dbo.tblserveruptime.year 
HAVING ( dbo.tblserveruptime.month = 4 ) 
       AND ( dbo.tblserveruptime.year = 2013 ) 

2 个答案:

答案 0 :(得分:0)

无论哪个字段为您提供物理服务器名称,请将该字段添加到GROUP BY语句并将其放在第一位。然后它将按服务器,月份和年份进行分组(正如您目前所拥有的那样)。我的猜测是你可能想要交换年份和月份,因为这样做比按月和年更有意义。

答案 1 :(得分:0)

好的,感谢所有试图提供帮助的人。我尝试将前后结果的图像放在一起,但我不能,因为我没有10个声望点。无论如何,我想我明白了。这是:

SELECT     AVG(dbo.tblServerUptime.Uptime) AS Uptime, 
CASE WHEN OS_TYPE = 'VMWare' THEN 'Virtual' ELSE 'Physical' END AS [Physical vs VM]
FROM         dbo.Server INNER JOIN
                      dbo.tblServerUptime ON dbo.Server.NAME = dbo.tblServerUptime.NAME
GROUP BY CASE WHEN OS_TYPE = 'VMWare' THEN 'Virtual' ELSE 'Physical' END