簡體   English   中英

如何將上一列復制到具有 NULL 值 SQL 的列中

[英]How to copy previous column into column with NULL values SQL

美好的一天,我有一張桌子。 它使用外鍵構建地理層次結構,因此使用連接,我創建了一個層次結構,但有些行沒有層次結構級別。 我必須將以前的列值復制到具有 NULL 值的單元格中。

層次結構是這樣的:

姓名1 | 類型1 | 姓名2 | 類型2 | 姓名3 | 類型3 | 姓名4 | 類型4 | 姓名5 | 類型5

遠東| 聯邦區| 阿穆爾 | 面積 | 別洛戈爾斯克 | 城市| 別洛戈爾斯克 | 城市| 別洛戈爾斯克 | 城市

這就是它的樣子,如果沒有 Name4/Type4 和 Name5/Type5 值,如您所見,Name3/Type3 值將被復制到下一列。 我的查詢是這樣的,我不知道下一步該怎么做。

select A.Name as Name1, A.Type as Type1, 
CAST(CASE when B.Name is null then A.Name else B.Name end AS nvarchar) as Name2, 
CAST(CASE when B.Type is null then A.Type else B.Type end AS nvarchar) AS Type2, 
CAST(CASE when C.Name is null then B.Name else C.Name end AS nvarchar) as Name3,
CAST(CASE when C.Type is null then B.Type else C.Type end AS nvarchar) as Type3,
CAST(CASE when D.Name is null then C.Name else D.Name end AS nvarchar) as Name4,
CAST(CASE when D.Type is null then C.Type else D.Type end AS nvarchar) as Type4,
CAST(CASE when E.Name is null then D.Name else E.Name end AS nvarchar) as Name5,
CAST(CASE when E.Type is null then D.Type else E.Type end AS nvarchar) as Type5
from [dbo].[DIM_Geography] AS A
left join [dbo].[DIM_Geography] AS B
on A.ID = B.ParentID
left join [dbo].[DIM_Geography] AS C
on B.ID = C.ParentID
left join [dbo].[DIM_Geography] AS D
on C.ID = D.ParentID
left join [dbo].[DIM_Geography] AS E
on D.ID = E.ParentID;

我還在圖像中附加了表格結構。

1

如果您可以確定要開始的 id,那么您可以使用遞歸 CTE。
然后是pivot的結果。

例子:

;with RCTE as  (
  -- the seed query to start the recursion
  select ID, parentID,  Name, [Type]
  , 1 as lvl
  , ID as baseID
  from [dbo].[DIM_Geography]
  where parentID is null

  union all

  -- the recursion, where the CTE uses itself
  select t.ID, t.parentID,  t.Name, t.[Type]
  , c.lvl + 1
  , c.baseID
  from RCTE c
  join [dbo].[DIM_Geography] t
    on t.parentID = c.ID
  where c.lvl < 5
)
select 
  max(case when lvl=1 then Name end) as Name1
, max(case when lvl=1 then [Type] end) as Type1
, max(case when lvl=2 then Name end) as Name2
, max(case when lvl=2 then [Type] end) as Type2
, max(case when lvl=3 then Name end) as Name3
, max(case when lvl=3 then [Type] end) as Type3
, max(case when lvl=4 then Name end) as Name4
, max(case when lvl=4 then [Type] end) as Type4
, max(case when lvl=5 then Name end) as Name5
, max(case when lvl=5 then [Type] end) as Type5
from RCTE
group by baseID;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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