工作上需要,將Table中相同的父ID【Parent_Id 欄位】,找出其最新一筆子ID【id 欄位】內容。
原始資料內容如下:
方法一(create function):
create function Concat (@Col1 int)
returns varchar(1000)
as
begin
declare @resultStr varchar(1000)
select top 1 @resultStr =[id] + '' from dbo.CheckList_Change where Parent_Id = @Col1 order by Create_Date desc
return @resultstr
end
Select Parent_Id,dbo.Concat(Parent_Id) as id from dbo.CheckList_Change
group by Parent_Id
order by Parent_Id
註:For SQL Server 2000以上,下面有產生create function位置畫面
===================================================================================================
方法二(FOR XML PATH):
SELECT T1.Parent_Id,(
SELECT top 1 [id] + '' FROM dbo.CheckList_Change T2 WHERE T2.Parent_Id = T1.Parent_Id order by Create_Date desc FOR XML PATH('')) AS [id]
FROM dbo.CheckList_Change T1
GROUP BY Parent_Id
order by Parent_Id
註:For SQL Server 2005以上,語法可參考 My blog
====================================================================================================
方法三(最簡單也最有效率,但往往忽略這方式):
select Parent_Id,MAX(Id) as id
from dbo.CheckList_Change
group by Parent_Id
order by Parent_Id
執行畫面:
產生create function畫面: