I have a table that contains data as per below script.
What i would like to archive, is the previous months amount. For monthly policy, So that the data can look something like this:
CREATE TABLE [dbo].[#dummy](
[Policy] [nvarchar](255) NULL,
[BatchMonth] [nvarchar](255) NULL,
[Amount] [float] NULL
) ON [PRIMARY]
INSERT INTO [dbo].[#dummy]
([Policy]
,[BatchMonth]
,[Amount])
VALUES
('A', 7, 100)
,('A', 8, 205)
,('A', 9, 350)
,('A', 10, 470)
,('A', 11, 590)
GO
select * from #dummy
drop table #dummy
November 9, 2019 at 5:22 pm
I think this might work:
select #dummy.Policy,#dummy.batchmonth, #dummy.Amount,isnull(#dummy2.Amount,0) as previousbatchmonth from #dummy left outer join #dummy #dummy2
on #dummy.Policy=#dummy2.Policy
and ((cast(#dummy.BatchMonth as int)-cast (#dummy2.BatchMonth as int )=1)
or (#dummy.BatchMonth=12 and #dummy2.BatchMonth=1))
Others may find fault with this solution or have better solutions. In particular the last line is a workaround. You may also wish to include an order by.
This solution will have problems if there is no data for a particular month. Will you always have data for each month?
November 9, 2019 at 7:40 pm
Yes each month will have data. I will let know if that works
Unless you're using a super old version of SQL Server, this should work fine:
SELECT [Policy]
, BatchMonth
, Amount
, LAG(Amount,1) OVER (PARTITION BY [Policy] ORDER BY BatchMonth) AS PrevMonthAmount
FROM #dummy
ORDER BY [Policy], BatchMonth;
November 10, 2019 at 7:09 am
Its SQL Server 2016. Thanks, i used your query as the results are consistent.
This has solved my issue.
November 10, 2019 at 7:10 am
Works fine as well.. thanks..
November 10, 2019 at 6:53 pm
Are the datatypes for the sample table in the original post representative of what you have for the real table in production?
--Jeff Moden
Change is inevitable... Change for the better is not.
November 11, 2019 at 5:51 am
Hi Jeff
Yes the datatype is represented that way within the DB.
I'm also worried about Policy and BatchMonth. I will talk to the Database Administrator as Policy should be Char while BatchMonth should date. Thank you for your help guys..
November 11, 2019 at 1:10 pm
Hi Jeff
Yes the datatype is represented that way within the DB.
I'm also worried about Policy and BatchMonth. I will talk to the Database Administrator as Policy should be Char while BatchMonth should date. Thank you for your help guys..
That means that a Developer designed the table with Visual Studio or somesuch and knows or cares little about right sizing. if you talk to them about it, they'll probably misquote Knuth about the root of all evil, etc.
As you know, those datatypes really should be fixed.
--Jeff Moden
Change is inevitable... Change for the better is not.
Viewing 9 posts - 1 through 8 (of 8 total)
You must be logged in to reply to this topic. Login to reply