[英]Data Manipulation Row_Number() SQL SERVER
我需要一些有关SQL SERVER 2012中数据处理问题的指导和帮助。
这是我的数据的样子:
=================================================
YearMonth LocationCode New ValidTo
=================================================
201412 2020 1 201502
201501 2020 1 201503
201503 3030 1 201506
201506 3030 1 201509
问题描述
如果你看一下上面的表格,你会看到列YearMonth
, locationCode
, New
它告诉是否locationCode
是新换的行中的一个月。 ValidTo列显示对哪个ValidTo
YearMonth
有效。
例如,对于YearMonth
201412, locationCode
2020为1,这意味着此处为New
并且在ValidTo
201502之前, LocationCode
被视为New。
我的问题是,我需要将最早出现在YearMonth列中的每个LocationCode设为“ 1”,直到ValidTo YearMonth都为New。
目的:
=================================================
YearMonth LocationCode New ValidTo
=================================================
201412 2020 1 201502
201501 2020 1 201503
201503 3030 1 201506
201506 3030 0 201509
基本上,我需要找出每个LocationCode
的MIN()
,然后将其归类为NEW
,“ 1”,如果LocationCode
出现在MIN() YearMonth
和ValidTo
然后将New
的LocationCode
归类为“ 1”。
我怎样才能做到这一点? 上表提供了一个直观的示例。
我已经编辑了决赛桌,以使其更容易理解我的问题。
基本上, LocationCode
3030的MIN() Year
为201503, LocationCode
的有效期至201506,如Validto
列中所述。 如果LocationCode
3030出现在YearMonth
行的201505中,并带有VALIDTO
到201506,则我们也将其归类为New
(1)。
基本上,伪代码
SELECT
MIN(YearMonth),
LocationCode
from Tabl
如果LocationCode
在MIN(YearMonth)和ValidTO
内,则将其分类为1。我该怎么做?
请尝试以下查询以更新表:最里面的查询将计算每个LocationCode
的最小Yearmonth
,用于计算需要在ValidTo
列中更新为1的所有ValidTo
和LocationCode
。
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
用于演示的示例sql小提琴: http ://sqlfiddle.com/#!6 / 229d8
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.