透视SQL表与文本行

时间:2017-06-28 08:59:23

标签: sql-server pivot

我正在尝试透视微软SQL数据库表,但我无法让它工作。我能找到的例子是数字并添加或加入它们。

这是我到目前为止所获得的,但收效甚微:

select *
from 
(
  select CODE, LangID , Text
  from dbo.REJECT_CODES
) src
pivot
(
  Text
  for LangID  in ([1], [2], [3], [4])
) piv;

这是我想要转动的表的示例:

    Code    LangID  Text
--------------------------------------------
    1       1       Text1
    1       2       Text2  
    1       3       Text3
    1       4       Text4
    2       1       Text5
    2       2       Text6
    2       3       Text7
    2       4       Text8

这是我想得到的结果:

    Code    TextA    TextB    TextC    TextD
----------------------------------------------
    1       Text1    Text2    Text3    Text4
    2       Text5    Text6    Text7    Text8

2 个答案:

答案 0 :(得分:3)

试试这个:

create table #temp (code int, languageID int, text varchar(10))
    insert into #temp values 
    (1,1,'Text1'),
   (1,2,'Text2'), 
   (1,3,'Text3'), 
   (1,4,'Text4'), 
   (2,1,'Text5'), 
   (2,2,'Text6'), 
   (2,3,'Text7'), 
   (2,4,'Text8')




select CODE, [1] As TextA, [2] As TextB, [3] As TextC, [4] As TextD
from 
(
  select CODE, LanguageID , Text
  from #temp
) src
pivot
(
  max(Text)
  for LanguageID  in ([1], [2], [3], [4])
) piv;

OP:

CODE        TextA      TextB      TextC      TextD
----------- ---------- ---------- ---------- ----------
1           Text1      Text2      Text3      Text4
2           Text5      Text6      Text7      Text8

答案 1 :(得分:1)

尝试使用像max:

这样的聚合函数
declare @tmp table(   Code int,    LangID int, Text nvarchar(50))


insert into @tmp select 1,1,'Text1'
insert into @tmp select 1,2,'Text2'
insert into @tmp select 1,3,'Text3'
insert into @tmp select 1,4,'Text4'
insert into @tmp select 2,1,'Text5'
insert into @tmp select 2,2,'Text6'
insert into @tmp select 2,3,'Text7'
insert into @tmp select 2,4,'Text8'

select * from @tmp

select *
from 
(
  select CODE, LangID , Text
  from @tmp
) src
pivot
(
  max(Text)
  for LangID  in ([1], [2], [3], [4])
) piv;

结果:

+------+-------+-------+-------+-------+
| CODE |   1   |   2   |   3   |   4   |
+------+-------+-------+-------+-------+
|    1 | Text1 | Text2 | Text3 | Text4 |
|    2 | Text5 | Text6 | Text7 | Text8 |
+------+-------+-------+-------+-------+