TSQL,将行透视成单列

时间:2018-10-08 14:07:10

标签: tsql pivot

之前,我必须解决类似的问题:

这是我的主旨,为了另一个解决方案而变扁平: 我想在下面的示例中执行相同的操作,但由于没有排名,因此略有不同。

在我之前的示例中,表如下所示:

LocationID   Code    Rank
1            123     1
1            124     2
1            138     3
2            999     1
2            888     2
2            938     3

并且我能够使用此功能将我的行正确地放在单个列中。

-- Check if tables exist, delete if they do so that you can start fresh.
IF OBJECT_ID('tempdb.dbo.#tbl_Location_Taxonomy_Pivot_Table', 'U') IS NOT NULL
  DROP TABLE #tbl_Location_Taxonomy_Pivot_Table; 
IF OBJECT_ID('tbl_Location_Taxonomy_NPPES_Flattened', 'U') IS NOT NULL 
  DROP TABLE tbl_Location_Taxonomy_NPPES_Flattened; 

-- Pivot the original table so that you have 
SELECT *
INTO #tbl_Location_Taxonomy_Pivot_Table
FROM [MOAD].[dbo].[tbl_Location_Taxonomy_NPPES] tax
PIVOT (MAX(tax.tbl_lkp_Taxonomy_Seq) 
       FOR tax.Taxonomy_Rank in ([1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12],[13],[14],[15])) AS pvt
       -- ORDER BY Location_ID

-- Flatten the tables.
SELECT Location_ID
,max(piv.[1]) as Tax_Seq_1
,max(piv.[2]) as Tax_Seq_2
,max(piv.[3]) as Tax_Seq_3
,max(piv.[4]) as Tax_Seq_4
,max(piv.[5]) as Tax_Seq_5
,max(piv.[6]) as Tax_Seq_6
,max(piv.[7]) as Tax_Seq_7
,max(piv.[8]) as Tax_Seq_8
,max(piv.[9]) as Tax_Seq_9
,max(piv.[10]) as Tax_Seq_10
,max(piv.[11]) as Tax_Seq_11
,max(piv.[12]) as Tax_Seq_12
,max(piv.[13]) as Tax_Seq_13
,max(piv.[14]) as Tax_Seq_14
,max(piv.[15]) as Tax_Seq_15
-- JOIN HERE
INTO tbl_Location_Taxonomy_NPPES_Flattened
FROM #tbl_Location_Taxonomy_Pivot_Table piv
GROUP BY Location_ID

那么,这就是我在此示例中要使用的数据。

    LocationID  Foreign Key
    2           2
    2           670
    2           2902
    2           5389
    3           3
    3           722
    3           2905
    3           5561

所以我有一些格式如下的数据: 我之前在数据上使用过数据透视法-但不同之处在于它也有排名。有没有办法通过枢轴使我的外键以这种格式显示?

locationID   FK1  FK2  FK3  FK4
2            2    670 2902  5389
3            3    722 2905  5561

我要解决的另一种方法是这样的: 我可以查看的另一种方式是将值包含在: 该表格也是如此:

LocationID        Address_Seq
2                       670, 5389, 2902, 2,
3                       722, 5561, 2905, 3
etc

反正我可以使它保持不变吗?

ID         Col1    Col2    Col3    Col4
2           670     5389,   2902,     2  

1 个答案:

答案 0 :(得分:0)

添加排名列并逆转订单,应该可以为您提供所需的条件:

SELECT locationid, [4] col1, [3] col2, [2] col3, [1] col4
FROM  
(
SELECT locationid, foreignkey,rank from #Pivot_Table ----- temp table with a rank column 
) x
PIVOT (MAX(x.foreignkey) 
FOR  x.rank in ([4],[3],[2],[1]) )  pvt