如何从SQL Server中的数据透视表中找到平均值?

时间:2018-05-17 06:11:36

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

我正在尝试捕获给定范围之间的每小时交易。我需要确定平均交易的最后一周。

这里我面临一些问题。

    Below is my trail:
    [Table Structure]
    [Current Result]
    [Query]

SELECT * 
FROM (SELECT 
    CONVERT(DATE, TimeStamp) AS [Date],
    DATEPART(hour,TimeStamp) AS [Hour],
    sum(CASE WHEN Result = 'F' THEN 1    ELSE 0    END) AS FAIL 
     FROM TableName 
     where  TimeStamp between '2018-05-12 00:00:00' and '2018-05-24 23:00:00'
    GROUP BY CONVERT(DATE,TimeStamp), DATEPART(hour,TimeStamp)) AS HourlyData 

    PIVOT( SUM(FAILS) FOR [Hour] IN (    [8], [9], [10],[11], [12], [13], [14], [15], [16], [17], [18], [19], [20], [21], [22], [23])
    ) AS DatePivot
    -- avg([Hour]  ) over(partition by DATEPART(hour,TimeStamp)) Avg_Item

[Table strcture,Current result and expected result][1]

任何人请纠正我如何找到平均值?尝试使用Over子句但不确定我需要在脚本中添加哪个列。

  [1]: https://i.stack.imgur.com/DeQYY.jpg

1 个答案:

答案 0 :(得分:0)

下面的代码应该会给你预期的结果。

; WITH CTE AS
(
    SELECT * 
    FROM (SELECT 
        CONVERT(DATE, TimeStamp) AS [Date],
        DATEPART(hour,TimeStamp) AS [Hour],
        sum(CASE WHEN Result = 'F' THEN 1.0    ELSE 0.0    END) AS FAIL 
         FROM #tmp 
         where  TimeStamp between '2017-01-10 00:00:00' and '2018-05-24 23:00:00'
        GROUP BY CONVERT(DATE,TimeStamp), DATEPART(hour,TimeStamp)) AS HourlyData 
        PIVOT( SUM(FAIL) FOR [Hour] IN ( [8], [9], [10],[11], [12], [13], [14], [15], [16], [17], [18], [19], [20], [21], [22], [23])
        ) AS DatePivot
    )
    SELECT * 
    FROM (SELECT 
    CONVERT(VARCHAR(11), TimeStamp) AS [Date],
    DATEPART(hour,TimeStamp) AS [Hour],
    sum(CASE WHEN Result = 'F' THEN 1.0   ELSE 0.0    END) AS FAIL 
     FROM #tmp 
     where  TimeStamp between '2017-01-10 00:00:00' and '2018-05-24 23:00:00'
    GROUP BY CONVERT(VARCHAR(11),TimeStamp), DATEPART(hour,TimeStamp)) AS HourlyData 
    PIVOT( SUM(FAIL) FOR [Hour] IN ( [8], [9], [10],[11], [12], [13], [14], [15], [16], [17], [18], [19], [20], [21], [22], [23])
    ) AS DatePivot
    UNION ALL
    SELECT 'AVERAGE',AVG([8]),AVG([9]),AVG([10]),AVG([11]),AVG([12]),AVG([13]),AVG([14]),AVG([15]),AVG([16]),AVG([17]),AVG([18]),AVG([19]),
        AVG([20]),AVG([21]),AVG([22]),AVG([23])
FROM CTE