簡體   English   中英

數據處理Row_Number()SQL Server

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

問題描述

如果你看一下上面的表格,你會看到列YearMonthlocationCodeNew它告訴是否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

基本上,我需要找出每個LocationCodeMIN() ,然后將其歸類為NEW ,“ 1”,如果LocationCode出現在MIN() YearMonthValidTo然后將NewLocationCode歸類為“ 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的所有ValidToLocationCode

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM