[英]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.