Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
Demo
CREATE TABLE #Table1 ([Year] int, [Period] int, [Country] varchar(50), [Value] int) ; INSERT INTO #Table1 ([Year], [Period], [Country], [Value]) VALUES ('2016', '2', 'Morovia', '100'), ('2016', '9', 'Morovia', '100'), ('2016', '10', 'Elbonia', '-20'), ('2016', '10', 'Elbonia', '2000'), ('2016', '10', 'Elbonia', '200'), ('2016', '10', 'Elbonia', '-100'), ('2016', '10', 'Elbonia', '1000'), ('2016', '10', 'Morovia', '200'), ('2016', '10', 'Elbonia', '-200'), ('2016', '10', 'Elbonia', '-200'), ('2016', '10', 'Elbonia', '100'), ('2016', '10', 'Elbonia', '60'), ('2016', '10', 'Elbonia', '40'), ('2016', '11', 'Morovia', '200'), ('2016', '11', 'Elbonia', '100') ;WITH cte AS (SELECT year, period, country, Sum(value) AS sumvalue FROM #Table1 t GROUP BY year, period, country) SELECT a.Year, a.Period, a.Country, a.sumvalue + Isnull(Sum(b.sumvalue), 0) FROM cte a LEFT JOIN cte b ON a.Country = b.Country AND Datefromparts(b.[Year], b.Period, 1) IN ( Dateadd(mm, -1, Datefromparts(a.[Year], a.Period, 1)), Dateadd(mm, -2, Datefromparts(a.[Year], a.Period, 1)) ) GROUP BY a.Year, a.Period, a.Country, a.sumvalue
run
|
edit
|
history
|
help
0
b
sql
zani
Week 6 Data Base IET
extract part of a string
Caronas
database size
self join - SQL
TUAN 7_QLDT
elie homsi's code