asked on
CREATE TABLE testData
(
orgId int,
keyId int,
period date,
value varchar(100)
)
1 2001-08-01 400
1 2001-09-01 100
1 2001-10-01 100
1 2001-11-01 100
ASKER
declare @testData table
(
orgId int,
keyId int,
period date,
value varchar(100)
)
INSERT INTO @testData values
(1,1,'2001-08-01','400'),
(1,1,'2001-09-01','400'),
(1,1,'2001-10-01','400'),
(1,1,'2001-11-01','400'),
(1,2,'2001-09-01','300'),
(1,2,'2001-10-01','300'),
(1,2,'2001-11-01','300')
;with cte as
(
select a.orgId, a.Period, CAST(a.Value AS DECIMAL(10, 4)) value,
ROW_NUMBER() OVER(PARTITION BY a.orgId, a.Period ORDER BY a.Period, a.keyId) SeqNo
from @testData a
)
select a.orgId, a.Period, sum(case when a.SeqNo = 1 then a.Value else a.value *-1 end) value
from cte a
group by a.orgId, a.Period
ASKER
Microsoft SQL Server is a suite of relational database management system (RDBMS) products providing multi-user database access functionality.SQL Server is available in multiple versions, typically identified by release year, and versions are subdivided into editions to distinguish between product functionality. Component services include integration (SSIS), reporting (SSRS), analysis (SSAS), data quality, master data, T-SQL and performance tuning.
TRUSTED BY