我有这样的数据:
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 :(得分:1)
首先,您创建一个函数,该函数获取ID并返回您之后的字符串...
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
答案 1 :(得分:0)
下次,除了示例之外,还要写出所需的排序条件。试试这个:
select [id], [name], [date] from MyTable
where [date] is not null
order by [date]