简体   繁体   English

在SQL Server中仅转置少量列

[英]Transposing only few columns in SQL Server

I have 4 columns in my table like : 我的表中有4列,如:

key     cusi             isi             name
1      46644UAQ1         US46642EAV83      A
1      46644UAR9         XS0062104145      A
1      254206AC9                           A                               
2      05617YAJ8         US86359AXP38      B      
2      885220BP7                           B
2       null                               B
3      885220BP5         885220BP7345      c

the key and name column content is getting duplicated because of the cusi and isi column .I would like to transpose only few columns in this case cusi and isi column so that i get 1 record of id =1 and another one for id=2 .In my use case there can be at the max 3 ditinct cusi or 3 isi column. 由于cusi和isi列,密钥和名称列内容正在重复。我想在这种情况下只转换几列cusi和isi列,这样我得到1个id = 1的记录和另一个id = 2的记录。在我的用例中,最多可以有3个ditinct cusi或3个isi列。

The transpose table should like 转置表应该如此

  key name cusi1        cusi2       cusi3        isi1         isi2           isi3
    1    A   46644UAQ1    46644UAR9   254206AC9  US46642EAV83  XS0062104145   NULL 
    2    A   46644UAR9    05617YAJ8   885220BP7  US86359AXP38  NULL           NULL
   3    c   885220BP5     null        null       885220BP7345  NULL           NULL 

In some cases there might be only 1 row like in t he above example it is for key= 3 在某些情况下,可能只有1行,如上例所示,它适用于key = 3

i know that sql has PIVOT and UNPIVOT queries but i am not sure how to use it for transposing selecting columns of a table Any help would be of great help. 我知道sql有PIVOT和UNPIVOT查询,但我不知道如何使用它来转置选择表的列任何帮助都会有很大的帮助。 Thanks 谢谢

If you know that each key - name group will have a fixed number of records (three, based on the sample data you gave us), then an ordinary non pivot should work. 如果你知道每个key name组都有固定数量的记录(三个,基于你给我们的样本数据),那么一个普通的非透视应该可以工作。 In the query below, I make use of the row number to distinguish each of the three columns you want for cusi and isi in your result set. 在下面的查询中,我使用的行号的每个要在三列的区分cusiisi在结果集中。

SELECT t.key,
       t.name,
       MAX(CASE WHEN t.rn = 1 THEN cusi END) AS cusi1,
       MAX(CASE WHEN t.rn = 2 THEN cusi END) AS cusi2,
       MAX(CASE WHEN t.rn = 3 THEN cusi END) AS cusi3,
       MAX(CASE WHEN t.rn = 1 THEN isi  END) AS isi1,
       MAX(CASE WHEN t.rn = 2 THEN isi  END) AS isi2,
       MAX(CASE WHEN t.rn = 3 THEN isi  END) AS isi3
FROM
(
    SELECT key,
           cusi,
           isi,
           name,
           ROW_NUMBER() OVER(PARTITION BY key ORDER BY cusi) AS rn
    FROM yourTable
) t
GROUP BY t.key,
         t.name

Note that SQL Server also has a PIVOT function, which is an alternative to what I gave. 请注意,SQL Server也有一个PIVOT函数,这是我给出的替代。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM