我有一张桌子,
ID REFGROUP YEAR MONTH VALUE
--- ----- ------ ----- -----
1 1000 2018 1 10
2 1000 2018 2 8
3 1000 2018 3 12
4 2000 2018 1 6
5 2000 2018 2 8
6 2000 2018 3 1
我想按组和年份逐月获取平均值
ID REFGROUP YEAR MONTH VALUE
--- ----- ------ ----- -----
1 1000 2018 1 10
2 1000 2018 2 9
3 1000 2018 3 10
4 2000 2018 1 6
5 2000 2018 2 7
6 2000 2018 3 5
结果将在上方。对于第二个月,请获取前两个月的平均值。对于第三个月,Iw将按refgroup和year得到前三个月分组的平均值。
我每个月都尝试工会。这会降低性能。我将每年的时间都定为12个月。怎么写sql查询才能比我写的快。排雷要花费8分钟,这太花了
select 1 AS AMONTHH, REFGROUP,AYEAR, AVG(TOTAL) from BMS.FNC_W_PAYROL WHERE AMONTH<=1 GROUP BY REFGROUP,AYEAR
UNION
select 2 AS AMONTHH, REFGROUP,AYEAR, AVG(TOTAL) from BMS.FNC_W_PAYROL WHERE AMONTH<=2 GROUP BY REFGROUP,AYEAR
UNION
select 3 AS AMONTHH, REFGROUP,AYEAR, AVG(TOTAL) from BMS.FNC_W_PAYROL WHERE AMONTH<=3 GROUP BY REFGROUP,AYEAR
UNION
select 4 AS AMONTHH, REFGROUP,AYEAR, AVG(TOTAL) from BMS.FNC_W_PAYROL WHERE AMONTH<=4 GROUP BY REFGROUP,AYEAR
UNION
select 5 AS AMONTHH, REFGROUP,AYEAR, AVG(TOTAL) from BMS.FNC_W_PAYROL WHERE AMONTH<=5 GROUP BY REFGROUP,AYEAR
UNION
select 6 AS AMONTHH, REFGROUP,AYEAR, AVG(TOTAL) from BMS.FNC_W_PAYROL WHERE AMONTH<=6 GROUP BY REFGROUP,AYEAR
UNION
select 7 AS AMONTHH, REFGROUP,AYEAR, AVG(TOTAL) from BMS.FNC_W_PAYROL WHERE AMONTH<=7 GROUP BY REFGROUP,AYEAR
UNION
select 8 AS AMONTHH, REFGROUP,AYEAR, AVG(TOTAL) from BMS.FNC_W_PAYROL WHERE AMONTH<=8 GROUP BY REFGROUP,AYEAR
UNION
select 9 AS AMONTHH, REFGROUP,AYEAR, AVG(TOTAL) from BMS.FNC_W_PAYROL WHERE AMONTH<=9 GROUP BY REFGROUP,AYEAR
UNION
select 10 AS AMONTHH, REFGROUP,AYEAR, AVG(TOTAL) from BMS.FNC_W_PAYROL WHERE AMONTH<=10 GROUP BY REFGROUP,AYEAR
UNION
select 11 AS AMONTHH, REFGROUP,AYEAR, AVG(TOTAL) from BMS.FNC_W_PAYROL WHERE AMONTH<=11 GROUP BY REFGROUP,AYEAR
UNION
select 12 AS AMONTHH, REFGROUP,AYEAR, AVG(TOTAL) from BMS.FNC_W_PAYROL WHERE AMONTH<=12 GROUP BY REFGROUP,AYEAR
答案 0 :(得分:2)
我们可以在此处使用解析函数:
SELECT
ID, REFGROUP, YEAR, MONTH,
AVG(VALUE) OVER (PARTITION BY REFGROUP, YEAR ORDER BY MONTH) AVG_VALUE
FROM yourTable
ORDER BY
REFGROUP, YEAR, MONTH;