2011-01-20 60 views
1

我有這樣的數據:請幫幫我,怎麼做他的 - SQL查詢(SQL Server 2000中)

ID Name   Date 
1 kishore  18-jan-2010 
2 kishh  19-jan-2010 
3 kii   NULL 
4 kk   null 
5 k   19-jan-2010 

我應該得到這樣的結果:

ID Name   Date 
1 kishore  18-jan-2010 
2 kishh,kii,kk 19-jan-2010 
5 k    19-jan-2010 
+0

你能幫我解答嗎? – Kishh 2011-01-20 07:07:50

+0

不,我是MySQL專家,不是SQL-Server-2000。對不起兄弟,*嗅*。 – shamittomar 2011-01-20 07:09:34

回答

1

首先,創建一個函數,它接受一個I​​D,並返回你後面的字符串...

CREATE FUNCTION dbo.StringFromID(@id int) 
RETURNS varchar(8000) 
AS 
BEGIN 
    DECLARE @value varchar(8000) 
    DECLARE @date datetime 
    SELECT @date = [date], @value = [name] 
    FROM test_data WHERE [id] = @id 

    WHILE EXISTS ( SELECT * FROM test_data 
      WHERE [id] = @id + 1 
      AND [date] IS NULL) 
    BEGIN 
     SELECT @value = @value + ',' + [name] 
     FROM test_data 
     WHERE [id] = @id + 1 

     SELECT @id = @id + 1 
    END 
    RETURN @value 
END 

然後調用該函數並顯示結果。

SELECT [id], dbo.StringFromID(t.[id]) 'Name', [date] 
FROM test_data t 
WHERE [date] IS NOT NULL 
0

下一次,除了例子之外,寫出所需的排序標準。試試這個:

select [id], [name], [date] from MyTable 
where [date] is not null 
order by [date]