简体   繁体   English

T-SQL:将列转换为行并插入/更新另一个表

[英]T-SQL: convert columns to rows and insert/update another table

I have to update data from #data table to #tests table in desired format.我必须以所需的格式将数据从 #data 表更新到 #tests 表。 I am not sure how I would archive result using T-SQL query?我不确定如何使用 T-SQL 查询归档结果?

NOTE: Temp tables have only 3 columns for sample purpose only but real table have more than 50 columns for each set.注意:临时表只有 3 列仅用于示例目的,但实际表每组有 50 多列。

Here is what my tables look like,这是我的桌子的样子,

IF OBJECT_ID('tempdb..#tests') IS NOT NULL 
    DROP TABLE #tests
GO

CREATE TABLE #tests
(
    id int,
    FirstName varchar(100),
    LastName varchar(100),
    UniueNumber varchar(100)
)

IF OBJECT_ID('tempdb..#data') IS NOT NULL 
    DROP TABLE #data
GO

CREATE TABLE #data
(
    id int,
    FirstName1 varchar(100),
    LastName1 varchar(100),
    UniueNumber1 varchar(100),
    FirstName2 varchar(100),
    LastName2 varchar(100),
    UniueNumber2 varchar(100),
    FirstName3 varchar(100),
    LastName3 varchar(100),
    UniueNumber3 varchar(100),
    FirstName4 varchar(100),
    LastName4 varchar(100),
    UniueNumber4 varchar(100),
    FirstName5 varchar(100),
    LastName5 varchar(100),
    UniueNumber5 varchar(100),
    FirstName6 varchar(100),
    LastName6 varchar(100),
    UniueNumber6 varchar(100),
    FirstName7 varchar(100),
    LastName7 varchar(100),
    UniueNumber7 varchar(100)
)

INSERT INTO #data 
VALUES (111, 'Tom', 'M', '12345', 'Sam', 'M', '65432', 'Chris', 'PATT', '54656', 'Sean', 'Meyer', '865554', 'Mike', 'Max', '999999', 'Tee', 'itc', '656546444', 'Mickey', 'Mul', '65443231')

INSERT INTO #data  
VALUES (222, 'Kurr', 'P', '22222', 'Yammy', 'G', '33333', 'Saras', 'pi', '55555', 'Man', 'Shey', '666666', 'Max', 'Dopit', '66666678', '', '', '', '', '', '')

INSERT INTO #data 
VALUES (333, 'Mia', 'K', '625344', 'Tee', 'TE', '777766', 'david', 'mot', '4444444', 'Jeff', 'August', '5666666', 'Mylee', 'Max', '0000000', '', '', '', 'Amy', 'Marr', '55543444')

SELECT * 
FROM #data

I want to insert/update data into #tests table from #data table.我想将数据从#data 表插入/更新到#tests 表中。 Insert data into #tests table if id and UniqueNumber combination does not exists from #data table.如果 #data 表中不存在 id 和 UniqueNumber 组合,则将数据插入到 #tests 表中。 If combination exists then update data into #tests table from #data table如果存在组合,则将数据从 #data 表更新到 #tests 表

This is desired output into #tests table这是所需的 output 进入#tests 表

在此处输入图像描述

One way is to query each group of columns separately and UNION the results一种方法是分别查询每组列并UNION结果

SELECT 
    id int,
    FirstName1 as FirstName,
    LastName1 as LastName,
    UniueNumber1 AS SSN
FROM #data
UNION 
SELECT 
    id int,
    FirstName2 as FirstName,
    LastName2 as LastName,
    UniueNumber2 AS SSN
FROM #data
UNION 
...

There's not a way to cleanly "loop through" the 7 groups of columns - you'll spend more time building a loop to create the query dynamically than just copying and pasting the query 6 times and changing the number.没有办法干净地“循环”这 7 组列 - 您将花费更多时间构建循环以动态创建查询,而不仅仅是复制和粘贴查询 6 次并更改数字。

Of course, it's best to avoid the type of structure you have in #data now if at all possible.当然,如果可能的话,最好避免现在#data中的结构类型。

Here is an option that will dynamically UNPIVOT your data without using Dynamic SQL这是一个选项,可以在不使用动态 SQL 的情况下动态地 UNPIVOT 您的数据

This is assuming your columns end with a NUMERIC ie FirstName##这是假设您的列以 NUMERIC 结尾,即FirstName##

Example例子

Select ID
      ,FirstName
      ,LastName
      ,UniueNumber
 From  (
        SELECT A.ID
              ,Grp
              ,Col = replace([Key],Grp,'')
              ,Value
        FROM #data A
        Cross Apply (
                        Select [Key]
                              ,Value
                              ,Grp = substring([Key],patindex('%[0-9]%',[Key]),25)
                         From OpenJson( (Select A.* For JSON Path,Without_Array_Wrapper  ) ) 
                    ) B
       ) src
 Pivot ( max(Value) for Col in ([FirstName],[LastName],[UniueNumber]) ) pvt
 Order By ID,Grp

Results结果

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM