如何合并2个表以使结果展平/合并?

时间:2013-10-21 22:56:23

标签: sql sql-server sql-server-2008 tsql sql-server-2005

我有以下2个表

表1:

TID         |Traning
---------------------------
1           |Training 1
2           |Training 2
3           |Training 3

表2:

ID      |TID        |Status
-----------------------------------
1234567 |1          |1
1234567 |2          |1
1234567 |3          |1

我想构建一个新视图,使得结果如下所示,

结果:

ID      |[Training 1 Status] |[Training 2 Status] |[Training 3 Status]
------------------------------------------------------------------------------
1234567 |1                   |1                   |1

如何在SQL Server中实现此目的?

谢谢!

2 个答案:

答案 0 :(得分:0)

CREATE TABLE #table1
    (
      ID VARCHAR(10) ,
      TID INT ,
      Status INT
    )
CREATE TABLE #table2 ( TID INT, Training varchar(10) )

--DROP TABLE #table1,#table2


INSERT INTO #table1
        ( ID, TID, Status )
SELECT  '1234567' AS [ID] ,
        '1' AS [TID] ,
        '1' AS [Status]
UNION ALL
SELECT  '1234567' AS [ID] ,
        '2' AS [TID] ,
        '1' AS [Status]
UNION ALL
SELECT  '1234567' AS [ID] ,
        '3' AS [TID] ,
        '1' AS [Status] 

INSERT  INTO #table2
        ( TID ,
          [Training]
        )
        SELECT  '1' AS [TID] ,
                'Training 1' AS [Training]
        UNION ALL
        SELECT  '2' AS [TID] ,
                'Training 2' AS [Training]
        UNION ALL
        SELECT  '3' AS [TID] ,
                'Training 3' AS [Training] 


SELECT  *
FROM    #table1


SELECT  *
FROM    #table2;



WITH temp_CTE  AS (SELECT  a.ID,b.TID,a.[Status] AS [Training Status]
FROM    #table1 a INNER JOIN #table2 b ON a.TID=b.TID)



SELECT  ID ,
        [1] AS [Training1] ,
        [2] AS [Training2] ,
        [3] AS [Training3]
FROM    ( SELECT    ID ,
                    TID ,
                    [Training Status]
          FROM       temp_CTE
        ) p PIVOT
( MAX([Training Status]) FOR tid IN ( [1], [2], [3] ) ) AS pvt

上面代码中你真正需要的是pivot和join命令,前面的代码就是我创建表格所以我可以试验数据。

答案 1 :(得分:0)

试试这个:

   SELECT ID,[1] AS [Training 1 Status] , [2] AS [Training 2 Status],[3] AS [Training 3 Status] FROM 
(SELECT DISTINCT Table_2.[ID],Table_2.TID,Table_2.[Status] FROM Table_1 INNER JOIN 
Table_2 ON Table_1.TID=Table_2.TID)  [Source_Tab] PIVOT 
(MAX([Status]) FOR [TID] IN ([1],[2],[3])) AS [Pivot_Tab];