合并2个表中的数据并旋转其中1个表中的数据

时间:2018-09-05 11:57:36

标签: sql sql-server

我目前的状况:

TableA
----------
SN     Date          OpsID
1234   2018-02-12    1
1324   2018-02-12    2
2134   2018-02-13    3

TableB
----------
Name     String      Number      OpsID
Value1   Hello       NULL        1
Value2   NULL        1111        1
Value3   Apples      NULL        1
Value1   There       NULL        2
Value2   NULL        2222        2
Value3   Pears       NULL        2
Value1   Baby        NULL        3
Value2   NULL        3333        3
Value3   Bananas     NULL        3

...我正在寻找的结果是:

SN    Date       Value1   Value2   Value3
1234  2018-02-12 Hello    1111     Apples
1324  2018-02-12 There    2222     Pears
2134  2018-02-13 Baby     3333     Bananas

我运行的查询显然是错误的,因为我主要获取的是NULL,而仅获取值数据,但是无论如何这里都是这样:

SELECT SN,Date,Value1,Value2,Value3
FROM(
   SELECT TableA.SN,
          TableA.Date,
          TableB.Name,
          TableB.String,
          TableB.Number
   FROM TableA,TableB
   WHERE
     TableA.OpsID = TableB.OpsID
   ORDER BY Date ASC
)Temp
PIVOT(
   MAX(Value)
   FOR Name in(
     Value1,Value2,Value3
   )
)PIV

请注意,Value1和Value3始终为VARCHAR,而Value2始终为INT

2 个答案:

答案 0 :(得分:1)

您将String和Number组合到子查询的单个列中,然后将值旋转回它们自己的列中,如下所示:

SELECT SN, Date, Value1, CAST(Value2 AS INT) Value2, Value3 
FROM 
(
    SELECT a.SN, a.Date, B.Name, ISNULL(b.String, CAST(b.Number AS VARCHAR(10))) Value
    FROM TableA A
    INNER JOIN TableB B ON A.OpsID = B.OpsID
)sq1
PIVOT (MAX(Value) FOR Name IN ([Value1], [Value2], [Value3]))sq2

答案 1 :(得分:0)

您可以进行条件聚合:

select a.SN, a.date,
       max(case when b.Name = 'Value1' then coalesce(b.String, cast(b.Number as varchar(255))) end) as Value1,
       max(case when b.Name = 'Value2' then coalesce(b.String, cast(b.Number as varchar(255))) end) as Value2,
       max(case when b.Name = 'Value3' then coalesce(b.String, cast(b.Number as varchar(255))) end) as Value3
from tablea a inner join
     tableb b
     on b.OpsID = a.OpsID
group by a.SN, a.date;