我正在努力解决这个问题,这里是表格设置:
date | time | count
----------------------------
12/12/2015 | 0:00 | 8
12/12/2015 | 1:00 | 19
12/12/2015 | 2:00 | 36
12/13/2015 | 0:00 | 12
12/13/2015 | 1:00 | 22
12/13/2015 | 2:00 | 30
12/14/2015 | 0:00 | 14
12/14/2015 | 1:00 | 26
12/14/2015 | 2:00 | 38
我希望我的查询返回的内容是这样的:
date | time | count | DAY | AVG/HR | AVG/DAY
---------------------------------------------------------
12/12/2015 | 0:00 | 8 | MONDAY | 11.33 | 63
12/12/2015 | 1:00 | 19 | MONDAY | 22.33 | 63
12/12/2015 | 2:00 | 36 | MONDAY | 34.67 | 63
12/13/2015 | 0:00 | 12 | TUESDAY | 11.33 | 64
12/13/2015 | 1:00 | 22 | TUESDAY | 22.33 | 64
12/13/2015 | 2:00 | 30 | TUESDAY | 34.67 | 64
12/14/2015 | 0:00 | 14 | WEDNESDAY | 11.33 | 78
12/14/2015 | 1:00 | 26 | WEDNESDAY | 22.33 | 78
12/14/2015 | 2:00 | 38 | WEDNESDAY | 34.67 | 78
所以基本上就是返回所有行(表中会有数月的数据,每天有24条记录/小时)。并添加星期几字段,每小时计数的平均值以及每周平均每天的计数。最后两个是我正在努力的。以下是我到目前为止的情况:
SELECT DATE, TIME, COUNT,
TO_CHAR(DATE, 'DAY'),
(SELECT AVG(t2.COUNT)
FROM tableXX t2
WHERE t2.time = t1.time
GROUP BY t2.time) AS AvgPerHr
(SELECT AVG(t2.COUNT)
FROM tableXX t2
WHERE TO_CHAR(t2.DATE, 'DAY') = TO_CHAR(t1.DATE, 'DAY')
GROUP BY TO_CHAR(t2.DATE, 'DAY')) AS AvgPerDay
FROM tableXX t1
ORDER BY DATE, TO_DATE(TIME, 'hh24:mi') ASC;
任何建议都会受到赞赏,上面的查询会返回数据,但绝对不准确。
答案 0 :(得分:2)
这可以通过使用分析函数来解决。
SELECT DATE, TIME, COUNT,
TO_CHAR(DATE, 'DAY'),
AVG(t1.COUNT)
OVER (PARTITION BY TIME) AS AvgPerHr,
AVG(t1.COUNT)
OVER (PARTITION BY TO_CHAR(DATE, 'DAY')) AS AvgPerDay
FROM tableXX t1
ORDER BY DATE, TO_DATE(TIME, 'hh24:mi') ASC;
答案 1 :(得分:1)
尝试:
SELECT "DATE", "TIME", "COUNT", TO_CHAR(DATE, 'DAY') "DAY,
avg( "COUNT" ) Over (partition by "TIME" ) "AVG/HR",
SUM( "COUNT" ) Over (partition by "DATE" ) "AVG/DAY"
FROM tablexx
ORDER BY 1;
我使用SUM( "COUNT" )
代替AVG( "COUNT" )
,因为您示例的第一行中的63似乎是每天的总和,而不是平均值。