如何在sql中更新每天平均每周值的列

时间:2018-04-25 01:15:20

标签: sql sql-server

我有下表。我插入了一个名为df.lookup(r.index,r['0'].astype(int).astype(str)) Out[106]: array(['S', 'C', 'C', 'S', 'R'], dtype=object) 的列,我想在WeekValue列填充每行相同类别的每周平均值weekvalue
像:

impressionCnt

我试过

+-------------------------+----------+---------------+--------------+
|          Date           | category | impressioncnt | weekAverage  |
+-------------------------+----------+---------------+--------------+
| 2014-02-06 00:00:00.000 | a        |           123 |          100 |
| 2014-02-06 00:00:00.000 | b        |           121 |          200 |
| 2014-02-06 00:00:00.000 | c        |           99  |          300 |
| 2014-02-07 00:00:00.000 | a        |           33  |          100 |
| 2014-02-07 00:00:00.000 | b        |           456 |          200 |
| 2014-02-07 00:00:00.000 | c        |           54  |          300 |
| 2014-02-08 00:00:00.000 | a        |           765 |          100 |
| 2014-02-08 00:00:00.000 | b        |           78  |          200 |
| 2014-02-08 00:00:00.000 | c        |           12  |          300 |
| .....                   |          |               |              |
| 2014-03-01 00:00:00.000 | a        |           123 |          111 |
| 2014-03-01 00:00:00.000 | b        |           121 |          222 |
| 2014-03-01 00:00:00.000 | c        |           99  |          333 |
| 2014-03-02 00:00:00.000 | a        |           33  |          111 |
| 2014-03-02 00:00:00.000 | b        |           456 |          222 |
| 2014-03-02 00:00:00.000 | c        |           54  |          333 |
| 2014-03-03 00:00:00.000 | a        |           765 |          111 |
| 2014-03-03 00:00:00.000 | b        |           78  |          222 |
| 2014-03-03 00:00:00.000 | c        |           12  |          333 |
+-------------------------+----------+---------------+--------------+

要获取周数,请尝试按周工作周数和日期和类别进行分组,但这似乎不正确。如何编写SQL查询?谢谢!

enter image description here

1 个答案:

答案 0 :(得分:1)

鉴于您将来可能会添加更多数据,因此需要进行其他更新,您可能只想选择每周平均值:

SELECT
    Date,
    category,
    impressioncnt,
    AVG(impressioncnt) OVER
        (PARTITION BY category, DATEDIFF(d, 0, Date) / 7) AS weekAverage
FROM RetailTS
ORDER BY
    Date, category;