0

我有以下 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 中实现这一点?

谢谢!

4

2 回答 2

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

在上面的代码中,您真正需要的是数据透视和连接命令,前面的代码只是我创建表,以便我可以对数据进行试验。

于 2013-10-21T23:41:15.220 回答
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];
于 2013-10-22T08:41:18.733 回答