0

我有一个查询,我只想修改它(这个查询不是我写的)。

SELECT  CAST(DATEPART(yyyy, UTCTimeStamp) AS VARCHAR(4)) + '-'
        + CAST(DATEPART(mm, UTCTimeStamp) AS VARCHAR(2)) + '-'
        + CAST(DATEPART(dd, UTCTimeStamp) AS VARCHAR(2)) + ' '
        + CAST(DATEPART(hh, UTCTimeStamp) AS VARCHAR(2)) + ':00:000 - '
        + CAST(DATEPART(yyyy, UTCTimeStamp) AS VARCHAR(4)) + '-'
        + CAST(DATEPART(mm, UTCTimeStamp) AS VARCHAR(2)) + '-'
        + CAST(DATEPART(dd, UTCTimeStamp) AS VARCHAR(2)) + ' '
        + CAST(DATEPART(hh, UTCTimeStamp) AS VARCHAR(2)) + ':45:000' AS HourTime ,
        SUM(CASE WHEN ElapsedValue IS NULL THEN 1
                 ELSE 0
            END) AS NoData ,
        SUM(CASE WHEN ElapsedValue = 0 THEN 1
                 ELSE 0
            END) AS ZeroData
FROM    tblLive_TrendLog_15Min
WHERE   ISNULL(ElapsedValue, 0) = 0
GROUP BY CAST(DATEPART(yyyy, UTCTimeStamp) AS VARCHAR(4)) + '-'
        + CAST(DATEPART(mm, UTCTimeStamp) AS VARCHAR(2)) + '-'
        + CAST(DATEPART(dd, UTCTimeStamp) AS VARCHAR(2)) + ' '
        + CAST(DATEPART(hh, UTCTimeStamp) AS VARCHAR(2)) + ':00:000 - '
        + CAST(DATEPART(yyyy, UTCTimeStamp) AS VARCHAR(4)) + '-'
        + CAST(DATEPART(mm, UTCTimeStamp) AS VARCHAR(2)) + '-'
        + CAST(DATEPART(dd, UTCTimeStamp) AS VARCHAR(2)) + ' '
        + CAST(DATEPART(hh, UTCTimeStamp) AS VARCHAR(2)) + ':45:000'

当我运行此查询时,它将显示:

HourlyTime                          ZeroData       NULL    
2013-6-8 23:00:000 - 2013-6-8 23:45:000 0   40    
2013-6-8 3:00:000 - 2013-6-8 3:45:000   0   52    
2013-6-8 7:00:000 - 2013-6-8 7:45:000   0   52    
2013-6-9 3:00:000 - 2013-6-9 3:45:000   0   52    
2013-6-9 4:00:000 - 2013-6-9 4:45:000   0   52    
2010-1-1 12:00:000 - 2010-1-1 12:45:000 0   36    
2010-1-1 13:00:000 - 2010-1-1 13:45:000 0   27    
2010-1-1 15:00:000 - 2010-1-1 15:45:000 0   30

基本上它是每小时计算零值和空值。如果您想了解更多信息,请点击以下链接: SQL Programming combine 4 rows into 1 and added 3 columns

现在,我只想在该查询中添加另一列,该列将计算是否有任何常量值,然后只显示常量值的数量(应该在 0 和 3 之间),例如,如果 2013-05-4 10 的值:30 在 2013-05-4 10:15 具有相同的值,那么在 ConstantData 列中应该是 1。基本上,每 15 分钟将该值与之前的值进行比较。

4

1 回答 1

0

我相信这是一个重复的问题,但只是想指出,使用 SQL 2012,您可以使用 FORMAT 函数大大简化查询:

SELECT  FORMAT(UTCTimeStamp ,'yyyy-MM-dd hh:00:000 - yyyy-MM-dd hh:45:000 ')AS HourTime ,
        SUM(CASE WHEN ElapsedValue IS NULL THEN 1
                 ELSE 0
            END) AS NoData ,
        SUM(CASE WHEN ElapsedValue = 0 THEN 1
                 ELSE 0
            END) AS ZeroData
FROM    tblLive_TrendLog_15Min
WHERE   ISNULL(ElapsedValue, 0) = 0
GROUP BY FORMAT(UTCTimeStamp ,'yyyy-MM-dd hh:00:000 - yyyy-MM-dd hh:45:000 ')
于 2013-06-27T17:53:31.737 回答