0

我有一个包含以下两列的表

ExportTime              | Manufacturer
2009-11-16 21:30:10.000 | IBM
2009-11-16 21:30:05.000 | VMWare
2009-11-16 21:30:12.000 | HP
2009-11-17 21:30:10.000 | Dell
2009-11-17 21:30:05.000 | VMWare
2009-11-17 21:30:12.000 | VMWare

我正在尝试创建一个图表来可视化虚拟机随时间的百分比。所以基本上我想要一个看起来像这样的 SQL 结果:

Date       | Virtual | Physical
2009-11-16 | 1       | 2
2009-11-16 | 2       | 1

这是我开始使用的基本查询,它为我提供了所有虚拟和所有物理

SELECT a.vmcount, b.physcount FROM (
    SELECT count(*) as vmcount FROM ServerDataHistorical
    WHERE Manufacturer LIKE 'VM%') a, (
    SELECT count(*) as physcount FROM ServerDataHistorical
    WHERE Manufacturer NOT LIKE 'VM%'
    ) b

我试过这个:

SELECT DATEADD(dd,(DATEDIFF(dd,0,ServerDataHistorical.ExportTime)),0) as date, a.vmcount, b.physcount FROM (
    SELECT count(*) as vmcount FROM ServerDataHistorical
    WHERE Manufacturer LIKE 'VM%') a, (
    SELECT count(*) as physcount FROM ServerDataHistorical
    WHERE Manufacturer NOT LIKE 'VM%'
    ) b,
    ServerDataHistorical
GROUP BY DATEADD(dd,(DATEDIFF(dd,0,ServerDataHistorical.ExportTime)),0)

它告诉我 vmcount 无效,因为它不包含在 group by 子句中。我也试过这个:

Declare @myDate varchar
Set @myDate = '2009-11-16'
SELECT ExportTime, a.vmcount, b.physcount FROM (
    SELECT count(*) as vmcount FROM ServerDataHistorical
    WHERE Manufacturer LIKE 'VM%' AND ExportTime LIKE @myDate + '%') a, (
    SELECT count(*) as physcount FROM ServerDataHistorical
    WHERE Manufacturer NOT LIKE 'VM%' AND ExportTime LIKE @myDate + '%'
    ) b,
    ServerDataHistorical
Group by ExportTime

我以为我只是以编程方式逐步遍历日期并获取数字,但这会产生与最后一个相同的错误。

4

1 回答 1

2

使用条件求和,您的基本查询会简单得多:

SELECT sum(case when sdh.Manufacturer like 'VM%' then 1 else 0 end) as vmcount,
       sum(case when sdh.Manufacturer not like 'VM%' then 1 else 0 end) as physical
FROM ServerDataHistorical sdh

如果你想要这个日期,只需添加一个group by子句:

SELECT cast(sdh.ExportTime as date) as thedate,
       sum(case when sdh.Manufacturer like 'VM%' then 1 else 0 end) as vmcount,
       sum(case when sdh.Manufacturer not like 'VM%' then 1 else 0 end) as physical
FROM ServerDataHistorical sdh
group by cast(sdh.ExportTime as date)
order by 1;

而且,如果您希望在特定日期期间使用此功能,只需添加一个where子句:

where ExportTime >= cast(@myDate as datetime) and
      ExportTime < cast(@MyDate as datetime) + 1

顺便说一句,变量 @MyDate 应该声明为 a dateor datetime。摆脱将日期/时间值存储在字符串中的习惯。

于 2013-05-07T19:33:23.017 回答