SQL动态数据透视动态数据

时间:2017-12-26 07:23:13

标签: sql-server pivot

我正在使用SQL Server数据库并拥有以下表格

表"数据"

   ------------------
   | Id | data_name |
   ------------------
   | 1  |Data 1     |
   | 2  |Data 2     |
   | 3  |Data 3     |
   | 4  |Data 4     |
   | 5  |Data 5     |
   ------------------

和表" Value_data"

   --------------------------------------------------------------------------------------------------------------
   | Id | data_id   | date       | col_1_type | col_1_name | col_1_value | col_2_type | col_2_name | col_2_value |
   --------------------------------------------------------------------------------------------------------------
   | 1  | 1         | 2017-01-01 | A          | Alpha      | 12          | B          | Beta       | 23          |
   | 2  | 1         | 2017-02-01 | A          | Alpha      | 32          | B          | Beta       | 42          |
   ---------------------------------------------------------------------------------------------------------------

我想做出如此结果

   -----------------------------------------------------------------
   |value_id | data_id | data_name | date       | A-Alpha | B-Beta |
   -----------------------------------------------------------------
   |1        | 1       | Data 1    | 2017-01-01 | 12      | 23     |
   |2        | 1       | Data 1    | 2017-02-01 | 32      | 42     |
   -----------------------------------------------------------------

我已多次搜索解决方案,我尝试过使用Pivot作为静态结果,

DECLARE @Data TABLE ( Id INT, data_name VARCHAR(10) )
INSERT INTO @Data VALUES
( 1 ,'Data 1'),
( 2 ,'Data 2'),
( 3 ,'Data 3'),
( 4 ,'Data 4'),
( 5 ,'Data 5')

DECLARE @Value_data TABLE (Id INT, data_id INT, [date] DATE, col_1_type VARCHAR(10), col_1_name VARCHAR(10), col_1_value INT, col_2_type VARCHAR(10), col_2_name VARCHAR(10), col_2_value INT)
INSERT INTO @Value_data VALUES
( 1, 1, '2017-01-01','A','Alpha','12','B','Beta','23'),
( 2, 1, '2017-02-01','A','Alpha','32','B','Beta','42')

;WITH CTE AS (
    select vd.Id value_id
        , vd.data_id 
        , d.data_name 
        , vd.[date]
        , vd.col_1_type + '-' +vd.col_1_name Col1
        , vd.col_1_value
        , vd.col_2_type + '-' +vd.col_2_name Col2
        , vd.col_2_value
    from @Value_data vd
        inner join @Data d on vd.data_id = d.Id
)   
SELECT * FROM CTE 
    PIVOT( MAX(col_1_value) FOR Col1 IN ([A-Alpha])) PVT_A
    PIVOT( MAX(col_2_value) FOR Col2 IN ([B-Beta])) PVT_B

但它对我使用连接表的数据效果不佳,因为我的数据库是动态的,任何人都有相同案例的解决方案吗?

0 个答案:

没有答案