SQL将表插入的值作为另一个表的列

时间:2014-06-18 08:02:46

标签: sql

      Table1                     Table2

      Id Name               Id Table1Id Value
      1  Some                1   1      value1
      2  Some1               2   2      value2
      3  Some2               3   3      value3
      4  Some3
          .
          .

我想结果:

     Some    Some1    Some2     Some3
     value1  value2   value3    NULL

当我在Table1中输入值时,我想看起来像table2的列,我该怎么做?

我想我正在寻找枢轴查询。

1 个答案:

答案 0 :(得分:0)

感谢您发布其他信息。根据您的说法,您正在寻找一个PIVOT语句,该语句将Table1中的每个name转换为一个列标题,其中包含表2中相应的value

查看以下SQL,它生成示例数据指示的输出。

CREATE TABLE #Table1 (ID INT, Name varchar(5))
CREATE TABLE #Table2 (ID INT, Table1ID INT, Value varchar(6))

INSERT INTO #Table1 (ID, Name) SELECT 1, 'Some'
INSERT INTO #Table1 (ID, Name) SELECT 2, 'Some1'
INSERT INTO #Table1 (ID, Name) SELECT 3, 'Some2'
INSERT INTO #Table1 (ID, Name) SELECT 4, 'Some3'

INSERT INTO #Table2 (ID, Table1ID, Value) SELECT 1, 1, 'Value1'
INSERT INTO #Table2 (ID, Table1ID, Value) SELECT 2, 2, 'Value2'
INSERT INTO #Table2 (ID, Table1ID, Value) SELECT 3, 3, 'Value3'

-- List of values to be columns
declare @cols nvarchar(max) 
select @cols = coalesce(@cols+N',', N'') + quotename(Name) from #Table1 order by ID
PRINT @Cols

declare @query varchar(MAX)
SET @query = '
SELECT * 
FROM 
  (
    SELECT T1.Name, T2.Value
    FROM 
        #Table1 T1
         INNER JOIN 
        #Table2 T2 ON 
            T1.ID = T2.Table1ID
  ) s
PIVOT
  (
  MAX(Value) FOR Name IN ('+@Cols+')
  )  p'

PRINT @query
EXEC (@query)

DROP TABLE #Table1
DROP TABLE #Table2