T-SQL-复制和转置数据

时间:2019-02-07 18:54:16

标签: sql sql-server tsql

我正在尝试将数据从一个表复制到另一个表,同时将其转置并将其合并到适当的行中,第二个表中的列则不同。

首次发布。是的,这对这里的每个人似乎都很简单。我已经尝试了几个小时来解决这个问题。我内部没有太多支持,并且在此论坛上学到了很多东西,并且在您的其他帮助示例中也取得了很多成就。我对此表示感谢。

表1中的数据采用这种格式。

Type    Date  Value
--------------------
First   2019  1
First   2020  2
Second  2019  3
Second  2020  4

表2已经填充了Date行并创建了列。它正在等待将表1中的值放在适当的列/行中。

Date  First Second
------------------
2019    1     3
2020    2     4

4 个答案:

答案 0 :(得分:1)

您可以进行条件聚合:

select date, 
       max(case when type = 'first' then value end) as first,
       max(case when type = 'Second' then value end) as Second
from table t
group by date;

之后,您可以使用cte

with cte as (
     select date, 
            max(case when type = 'first' then value end) as first,
            max(case when type = 'Second' then value end) as Second
     from table t
     group by date
)

update t2
      set t2.First = t1.First,
          t2.Second = t1.Second
from table2 t2 inner join
     cte t1
     on t1.date = t2.date;

答案 1 :(得分:1)

使用条件聚合

set_union

答案 2 :(得分:1)

要进行更新,我可以使用两个join

update  t2
    set first = tf.value,
        second = ts.value
    from table2 t2 left join
         table1 tf
         on t2.date = tf.date and tf.type = 'First' left join
         table1 ts
         on t2.date = ts.date and ts.type = 'Second'
    where tf.date is not null or ts.date is not null;

答案 3 :(得分:0)

好像您在PIVOT之后

 DECLARE @Table1 TABLE
    (
        [Type] NVARCHAR(100)
      , [Date] INT
      , [Value] INT
    );

DECLARE @Table2 TABLE(
[Date] int
,[First] int
,[Second] int
)

INSERT INTO @Table1 (
                          [Type]
                        , [Date]
                        , [Value]
                      )
VALUES ( 'First', 2019, 1 )
     , ( 'First', 2020, 2 )
     , ( 'Second', 2019, 3 )
     , ( 'Second', 2020, 4 );

INSERT INTO @Table2 (
                        [Date]
                    )
VALUES (2019),(2020)

--Show us what's in the tables
SELECT * FROM @Table1
SELECT * FROM @Table2

--How to pivot the data from Table 1 
SELECT * FROM   @Table1
    PIVOT (
              MAX([Value]) --Pivot on this Column
              FOR [Type] IN ( [First], [Second] ) --Make column where [Value] is in one of this
          ) AS [pvt] --Table alias

--which gives
--Date        First       Second
------------- ----------- -----------
--2019        1           3
--2020        2           4

--Using that we can update @Table2
UPDATE [tbl2]
SET [tbl2].[First] = pvt.[First]
    ,[tbl2].[Second] = pvt.[Second]
FROM   @Table1 tbl1
    PIVOT (
              MAX([Value]) --Pivot on this Column
              FOR [Type] IN ( [First], [Second] ) --Make column where [Value] is in one of this
          ) AS [pvt] --Table alias
INNER JOIN @Table2 tbl2 ON [tbl2].[Date] = [pvt].[Date]

--Results from @Table 2 after updated
SELECT * FROM @Table2

--which gives
--Date        First       Second
------------- ----------- -----------
--2019        1           3
--2020        2           4