I need some guidance and help with a data manipulation question in SQL SERVER 2012.
This is how my data looks like:
=================================================
YearMonth LocationCode New ValidTo
=================================================
201412 2020 1 201502
201501 2020 1 201503
201503 3030 1 201506
201506 3030 1 201509
Problem description
if you look at the above table, you will see the column YearMonth
, locationCode
, New
which tells whether the locationCode
is new for the month in the row. The ValidTo column shows to which ValidTo
YearMonth
it is validto.
For the example, for YearMonth
201412, the locationCode
2020 is 1, which means here it is New
and that LocationCode
is considered New till ValidTo
201502.
My problem is that I need to make each LocationCode , that appears in the earliest YearMonth Column, to New, is this case "1" till the ValidTo YearMonth.
Objective:
=================================================
YearMonth LocationCode New ValidTo
=================================================
201412 2020 1 201502
201501 2020 1 201503
201503 3030 1 201506
201506 3030 0 201509
Basically, I need to find out the MIN()
for each LocationCode
and then categorize it as NEW
,"1" and if the LocationCode
appears within the MIN() YearMonth
and ValidTo
then categorize the LocationCode
in New
as "1".
How Can I do that? The above table provides a visual example.
I have edited my final table to make it simpler to understand my question.
Basically,the MIN() Year
for LocationCode
3030 is 201503 and the LocationCode
is valid till 201506 as demostrated in the Validto
Column. If the LocationCode
3030 were to appear in the YearMonth
row, 201505 with a VALIDTO
till 201506, then we classify it as New
(1) as well.
Basically,pseudocode
SELECT
MIN(YearMonth),
LocationCode
from Tabl
If LocationCode
, is in MIN(YearMonth) AND ValidTO
timeperiod then classify it as 1. How can I do this?
Please try the below query for updating the table: The inner most query calculates the minimum Yearmonth
per LocationCode
which is used to calculate all ValidTo
and LocationCode
s which need to be updated to 1 in ValidTo
column
update t2
set New= CASE when t1.ValidTo is null then 0 else 1 end
FROM tbl t2
LEFT JOIN
(
select t.ValidTo, t.locationCode
from tbl t inner join
(
select
MIN(YearMonth) as MYM,
LocationCode
from tbl
group by LocationCode
) g
on t.YearMonth=g.MYM and t.LocationCode=g.LocationCode
) t1
on t2.ValidTo=t1.ValidTo and t2.LocationCode=t1.LocationCode
sample sql fiddle for demo: http://sqlfiddle.com/#!6/229d8
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.