SQL语句,每30天获取一次分组数据,按日期分组

时间:2013-05-07 19:28:46

标签: sql sql-server-2008 datetime group-by

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

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

我正在尝试创建一个图表来显示VM随时间的百分比。所以基本上我想要一个如下所示的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

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

1 个答案:

答案 0 :(得分: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应该声明为datedatetime。摆脱将日期/时间值存储在字符串中的习惯。