枢轴未给出预期结果

时间:2019-03-21 17:40:13

标签: sql sql-server tsql

我正在使用数据透视和非透视,但我得到了预期的输出结果

这是我的样本数据集

  

表1

id    c_code
-----------------
123     1
456     1
  

表2

id   c_code   i_t_code   i_code  
----------------------
123     1     TWinc     10              
123     1     TBinc     20      
123     1     TSinc     30      
  

表3

i_code   i_t_code   i_name 
------------------------------
10        TWinc        abc         
20        TBinc        xyz
30        TSinc        pqr

这是我的查询

  

查询

select * from (
    select id,inc,i_t_code from (
        select a.id,b.i_name,cast(b.i_code AS                        
        VARCHAR(128)) as i_code,b.i_t_code
        from 
        table_1 a
        join 
        table_2 b 
        on a.id= b.id
        and 
        a.c_code = b.c_code 
        join
        tabl_3 c on c.i_code = b.i_code 
        and 
        c.i_t_code = b.i_t_code 

        on a.i_code = b.i_code 
) d 
Unpivot
(
 inc for details in (i_name,i_code)
) as unpt) as uppt_res
PIVOT
(
   max(inc)
   FOR [i_t_code] IN ([TWinc],[TBinc],[TSinc])
) AS P
  

预期输出:

id        TWinc_n   TWinc_c  TBinc_n  TBinc_c   TSinc_n   TSinc_c
------------------------------------------------------------
123         abc       10       xyz     20        pqr      30
  

实际输出:

 id         TWinc    TBinc   TSinc   
------------------------------------
123          abc      xyz     pqr   

该怎么做??

可以使用数据透视或其他任何解决方案

任何人都可以帮助解决此问题吗?

1 个答案:

答案 0 :(得分:0)

如果要停止将数据转换为列名并选择max(inc)时将相同数据项压缩在一起的枢轴,则必须对数据进行一些更改-可能最容易通过更改未透视数据的内容,以行号开头:

SELECT * FROM
(
   select stoneid, inc, CONCAT(inclusion_type_id, ROW_NUMBER()OVER(PARTITION BY inclusion_type_id ORDER BY inc)) as inclusion_type_id FROM
   (
       select 
           a.stoneid,
           b.inclusion_name,
           cast(b.inclusion_code AS VARCHAR(128)) as     inclusion_code,
           b.inclusion_type_id,
           b.inclusion_type_code  
       from 
           PACKET.STONE_LAB_INCLUSIONS a
           inner join 
           MASTER.INCLUSION_MASTER b 
           on 
               a.inclusion_code = b.inclusion_code and 
               a.inclusion_type_code = b.inclusion_type_code

           inner join 
           packet.stone_details c 
           on 
               c.stoneid = a.stoneid  and 
               c.certificate_code = a.certificate_code 
   ) d 
   UNPIVOT(inc for details in (inclusion_name,inclusion_code)) as unpt
) uppt_res
PIVOT
(
   MAX(inc)
   FOR [inclusion_type_id] IN ([TWinc1],[TWinc2],[TBinc1],[TBinc2],[TSinc1],[TSinc2])
) AS P

如果您希望列名相同,则可以为该查询的结果加上别名,而不是select *