我被要求创建一个按星期平均的临时数...以及邮政编码。该表有1500万行,并希望每个邮政编码41K缩短52周。这是前10行:
postal_code Local_date tempAvg_F tempMax_F tempMin_F 1001 2015-07-14 74 83 65 1001 2015-07-15 74 84 63 1001 2015-07-16 67 78 57 1001 2015-07-17 70 82 54 1001 2015-07-18 73 82 67 1001 2015-07-19 80 91 71 1001 2015-07-20 81 92 71 1001 2015-07-21 76 90 67 1001 2015-07-22 73 83 59 1001 2015-07-23 71 83 56
我已经查看了cte,AVG和group by,但是想知道使用FOR EACH LOOP是否会更好。如果有人能指出我正确的方向。
JJ
答案 0 :(得分:1)
但是想知道使用FOR EACH LOOP是否会更好
SQL世界中的循环/游标比基于集合的解决方案慢95%。
您可以使用简单的GROUP BY
:
SELECT postal_code
,[week] = DATEPART(wk, Local_date)
,[week_tempAvg_F] = AVG(tempAvg_F)
,[week_tempMax_F] = AVG(tempMax_F)
,[week_tempMin_F] = AVG(tempMin_F)
FROM #tab
GROUP BY postal_code,DATEPART(wk, Local_date)
ORDER BY postal_code, [week];
的 LiveDemo
强>
输出:
╔═════════════╦══════╦════════════════╦════════════════╦════════════════╗
║ postal_code ║ week ║ week_tempAvg_F ║ week_tempMax_F ║ week_tempMin_F ║
╠═════════════╬══════╬════════════════╬════════════════╬════════════════╣
║ 1001 ║ 29 ║ 71 ║ 81 ║ 61 ║
║ 1001 ║ 30 ║ 76 ║ 87 ║ 64 ║
╚═════════════╩══════╩════════════════╩════════════════╩════════════════╝