【问题标题】:How to display different values in same column into single Row in SQL server 2008如何在 SQL Server 2008 中将同一列中的不同值显示为单行
【发布时间】:2014-08-21 04:08:55
【问题描述】:

我有一个下面两个表

 ID      TextID     Description
 -------------------------------
 1        2          zzzz
 1        3          kkkk
 1        4          llll
 5        2          nnnn

 TextID      TextTypeID     
 -------------------------------
 1            R1
 2            R2
 3            R3
 4            R4

我想要使用 Case 语句的 ID 的结果,如下所示。请建议。

 ID      R1      R2    R3     R4
 ---------------------------------
  1      null   zzzz   kkkk  llll

【问题讨论】:

标签: sql-server


【解决方案1】:

我将表命名为 #a、#b 和 #c 感觉您没有提供名称。

create table #c
(ID int not null primary key)

insert into #c (ID)
select distinct ID
from #a

declare @TextTypeID char(2)
declare @sql varchar(max)

declare r_cursor cursor for
select distinct TextTypeID
from #b
order by TextTypeID

open r_cursor
fetch next from r_cursor into @TextTypeID

while @@FETCH_STATUS = 0
BEGIN
    set @sql = 'alter table #c add [' + @TextTypeID + '] char(4)'
    exec (@sql)

    set @sql = 'update c set [' + @TextTypeID + '] = a.[Description]
    from #c c
    join #a a on c.ID = a.ID
    join #b b on a.TextID = b.TextID
    where b.TextTypeID = '''+ @TextTypeID + ''''
    exec (@sql)

    fetch next from r_cursor into @TextTypeID
END

close r_cursor
deallocate r_cursor

select *
from #c

【讨论】:

    猜你喜欢
    • 2023-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-16
    • 2015-03-14
    • 2016-09-14
    • 1970-01-01
    相关资源
    最近更新 更多