sql—如何在列中使用唯一值连接配置单元中的两个表

dwbf0jvd  于 2021-05-29  发布在  Hadoop
关注(0)|答案(1)|浏览(279)

我在配置单元中有两个表,表1和表2具有以下值:
表1:表2:
日期价值日期价值
‘2016-01-01’……一……………‘2016-01-01’……二
“2016-01-01”……三个…………..“2016-01-01”……四个
'2016-01-01'…五
我需要连接两个表以创建第三个表(有三行):
日期…………………值1………………………值2
‘2016-01-01’………一……………二
‘2016-01-01’……三…………四
‘2016-01-01’……五
我试过很多办法,但都不管用。
任何想法。

koaltpgm

koaltpgm1#

DECLARE @table1 TABLE ([Date] Date, [Value] VarChar(10))
DECLARE @table2 TABLE ([Date] Date, [Value] VarChar(10))

INSERT INTO @table1([Date], [Value])
SELECT '2016-01-01', 'one'
UNION ALL
SELECT '2016-01-01', 'three'
UNION ALL
SELECT '2016-01-01', 'five'

INSERT INTO @table2([Date], [Value])
SELECT '2016-01-01', 'two'
UNION ALL
SELECT '2016-01-01', 'four'

SELECT [Date]   = t1.[Date],
       [Value1] = t1.[Value],
       [Value2] = t3.[Value]
FROM
(SELECT [Date]  = t.[Date],
        [Value] = t.[Value],
        [ID]    = ROW_NUMBER() OVER(ORDER BY t.[Date] DESC)
 FROM @table1 t) t1
OUTER APPLY
(
   SELECT TOP 1 t2.[Value]
   FROM
   (SELECT [Date]  = t.[Date],
           [Value] = t.[Value],
           [ID]    = ROW_NUMBER() OVER(ORDER BY t.[Date] DESC)
    FROM @table2 t) t2
   WHERE t2.[Date] = t1.[Date] 
     AND t2.[ID]   = t1.[ID]
) t3

相关问题