增长随时间变化最大值日期值 - 最小日期值

时间:2016-06-09 14:17:57

标签: sql sql-server sql-server-2008-r2

我创建了一个查询,它给了我以下数据,我试图根据输入的开始和结束日期获得随时间的增长。我想取MaxDate上的值 - 每个服务器和数据库的最小日期值。怎么会这样?

SName  DBName   Min Date                    MaxDate                     FileSizeGB
TW      RT      2016-01-01 18:00:01.373     NULL                        103
ERP     RT      2016-01-01 21:00:01.210     NULL                        121
VW      RT      2016-06-02 09:39:42.603     NULL                        115
TW      RT      NULL                        2016-06-05 18:00:00.960     104
VW      RT      NULL                        2016-06-05 18:00:01.017     115
ERP     RT      NULL                        2016-06-08 21:00:01.333     121

这是我当前的查询:

Select a.*,
SUM(FileSizeMB/1024) as GBSize
FROM DBinfo db2 INNER JOIN 
(
SELECT 
left(ServerName, len(ServerName)-1) as servername,
DatabaseName,
MIN(PollDate) as MinDate,
NULL as MaxDate
 from DBInfo db1
 Where DatabaseName IN (@dbname) AND left(ServerName, len(ServerName)-1)  IN (@servername)
 AND PollDate BETWEEN '2016-01-01' AND GETDATE()
 GROUP BY ServerName, DatabaseName
 ) a on  a.MinDate = db2.PollDate 
 WHERE left(db2.ServerName, len(db2.ServerName)-1) = a.servername and db2.DatabaseName = a.DatabaseName
 GROUP BY a.servername, a.DatabaseName, a.MinDate, a.MaxDate


 UNION ALL 

 Select a.*,
SUM(FileSizeMB/1024) as GBSize
FROM DBinfo db2 INNER JOIN 
(
SELECT
left(ServerName, len(ServerName)-1) as servername,
DatabaseName,
NULL as MinDate,
MAX(PollDate) as MaxDate
 from DBInfo
 Where DatabaseName IN (@dbname) AND left(ServerName, len(ServerName)-1)  IN (@servername)
 AND PollDate BETWEEN '2016-01-01' AND GETDATE()
 GROUP BY ServerName, DatabaseName
  ) a on  a.MaxDate = db2.PollDate 
 WHERE left(db2.ServerName, len(db2.ServerName)-1) = a.servername and db2.DatabaseName = a.DatabaseName
  GROUP BY a.servername, a.DatabaseName, a.MinDate, a.MaxDate

我觉得我的复杂程度超过了必要。非常感谢帮助。

1 个答案:

答案 0 :(得分:0)

你可以用这个

WITH DBMaxDate AS
(SELECT
    *
FROM
    (SELECT
        *
        ,ROW_NUMBER() OVER (PARTITION BY ServerName, DatabaseName ORDER BY PollDate DESC) rwn
    FROM
        DBInfo
    WHERE
        PollDate BETWEEN '2016-01-01' AND GETDATE()
    )
WHERE 
    rwn = 1
)
, DBMinDate AS
(SELECT
    *
FROM
    (SELECT
        *
        ,ROW_NUMBER() OVER (PARTITION BY ServerName, DatabaseName ORDER BY PollDate) rwn
    FROM
        DBInfo
    WHERE
        PollDate BETWEEN '2016-01-01' AND GETDATE()
    )
WHERE 
    rwn = 1 
)
SELECT 
    ServerName
    ,DatabaseName
    ,mi.PollDate as MinDate
    ,ma.PollDate as MaxDate
    ,ma.FileSizeMB/1024 - mi.FileSizeMB/1024 as FileSizeGB
FROM
    DBMaxDate ma
INNER JOIN
    DBMinDate mi
ON 
    ma.ServerName = mi.ServerName and ma.DatabaseName = mi.DatabaseName;