我有一个如下表。每个城市都会有一行,其中TYPE
= Active
和Month
= 0
,然后将有X
数的Push
行开始其中Month
= 0
转到Month
= X
。在下面的示例中,X
= 3
。
我需要创建一个查询来生成第二张表。
基本上,对于每个城市:
Active
= Push
的{{1}}和Month
值,然后将它们相加以获得0
= {{ 1}} Final
,取上个月的Month
值,并将其添加到第一张表中的月份0
的值中。我认为我必须使用Month
和Final
或Push
,但是我不确定如何或从哪里开始。
SQL Fiddle似乎不起作用,因此我包含了CREATE / INSERT语句以初始化第一个表。
编辑:我发现了SUM
-https://dbfiddle.uk/?rdbms=sqlserver_2014&fiddle=9dab5f207b97a318c7d0f26369a4b3ed。
OVER
ROLLUP
db<>fiddle
答案 0 :(得分:1)
您可以使用窗口功能:
select distinct city, 'final' as [type], [month],
sum(value) over (partition by city order by [month]) AS Value
from table t;
如样本数据所示,您只需要订购month
。
答案 1 :(得分:0)
请尝试以下查询:
SELECT city ,
'Final' AS Type ,
t.month ,
t.Value
FROM ( SELECT city ,
[type] ,
[month] ,
SUM(value) OVER ( PARTITION BY city
ORDER BY type ,
month ) AS Value
FROM #cities ) t
WHERE t.type = 'Push';
结果:
+-------+-------+-------+-------+
| city | Type | month | Value |
+-------+-------+-------+-------+
| one | Final | 0 | 215 |
| one | Final | 1 | 216 |
| one | Final | 2 | 210 |
| one | Final | 3 | 210 |
| three | Final | 0 | 404 |
| three | Final | 1 | 409 |
| three | Final | 2 | 401 |
| three | Final | 3 | 401 |
| two | Final | 0 | 358 |
| two | Final | 1 | 362 |
| two | Final | 2 | 357 |
| two | Final | 3 | 362 |
+-------+-------+-------+-------+
答案 2 :(得分:0)
我将使用聚合和累加总和来完成此操作
select city, 'final' as [type], [month],
sum(sum(value)) over (partition by city order by [month]) AS Value
from table t
group by city, month
order by city, month;
答案 3 :(得分:-1)
我没有测试此查询,但希望它将对您有所帮助。
CREATE TABLE NEWTABLE AS
SELECT a.CITY, 'Final', a.MONTH,
SUM(
(
SELECT x.VALUE
FROM TABLE1 x
WHERE x.MONTH <= a.MONTH
AND x.CITY = a.CITY
)
) AS VALUE
FROM TABLE1 a
WHERE a.TYPE = 'PUSH'
GROUP BY a.CITY, a.MONTH