如果数据不同,则将一列中的行转换为单独的列

时间:2017-05-05 09:32:31

标签: tsql sql-server-2008-r2

我的表是: enter image description here

我希望输出为:

enter image description here

1 个答案:

答案 0 :(得分:0)

你可以这样做,我没有睾丸希望它会起作用;)

create table #Result (
    ID nvarchar(10),
    [Date] datetime,
    [DrugIndex] int,
    Drug1 nvarchar(1000))

DECLARE @ID nvarchar(10),
        @Date datetime,
        @Drug nvarchar(1000)
DECLARE crResult CURSOR FOR SELECT ID,[Date],[Drug] FROM tblSource 
OPEN crResult
FETCH NEXT FROM crResult INTO @ID,@Date,@Drug
WHILE @@FETCH_STATUS=0
    BEGIN 
        IF EXISTS(SELECT * FROM #Result WHERE ID=@ID AND [Date]=@Date)
            BEGIN
                DECLARE @Index int
                SET @Index=(SELECT DrugIndex FROM #Result WHERE Id=@Id and [Date]=@Date)
                SET @Index=@Index+1
                DECLARE @sqlCmd nvarchar(1024)
                SET @sqlCmd='ALTER TABLE #Result ADD Drug'+CONVERT(nvarchar(10),@Index)+' nvarchar(1000)'
                EXECUTE (@sqlCmd)
                SET @sqlCmd='UPDATE #Result SET [DrugIndex]='+CONVERT(nvarchar(10),@Index)+', [Drug'+CONVERT(nvarchar(10),@Index)+
                    ']='''+@Drug+''' WHERE ID='+CONVERT(nvarchar(10),@ID)+''' AND [Date]='''+CONVERT(nvarchar(20),@Date)+''''
                EXECUTE (@sqlCmd)
            END
        ELSE 
            INSERT INTO #Result(ID,[Date],DrugIndex,[Drug1]) VALUES @ID,@Date,1,@Drug 
        FETCH NEXT FROM crResult INTO @ID,@Date,@Drug
    END
CLOSE crResult
DEALLOCATE crResult