1. 程式人生 > >開窗函式 Row_Number partition by 分類排序

開窗函式 Row_Number partition by 分類排序

背景, 目前在維護老專案, 但其中有bug.

原先的邏輯在對某個資料的分類編號時不對,導致結果不準確.

解決方案: 用開窗函式 row_number partition by 某個被分類的資料欄位, 然後 針對時間戳做個排序

因為在辦公室不方便弄, 只好回家自己憑記憶,把主要的點列出來.

以下是主要的表結構:

 
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[tblFeed]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[tblFeed](
	[key] [uniqueidentifier] NOT NULL CONSTRAINT [DF_tblFeed_key]  DEFAULT (newid()),
	[type] [int] NULL,
	[content] [varchar](1000) NULL,
	[createdStamp] [datetime] NOT NULL CONSTRAINT [DF_tblFeed_createdStamp]  DEFAULT (getdate()),
	[lastUpdatedStamp] [datetime] NOT NULL CONSTRAINT [DF_tblFeed_lastUpdatedStamp]  DEFAULT (getdate()),
	[parentkey] [uniqueidentifier] NULL,
	[ownerkey] [uniqueidentifier] NULL,
	[state] [int] NULL
) ON [PRIMARY]
END

主要涉及查詢的sql指令碼為:

SELECT a.* into #tmpFeed FROM tblFeed a
inner join tblFeed b
	on a.[parentkey]=b.[key]
    and a.ownerKey='B588D659-CF0F-4A28-AD2B-3D9B9FAFC357'
    and b.ownerkey='B588D659-CF0F-4A28-AD2B-3D9B9FAFC357'
    and a.type=1
    and b.type=0

 --select * from #tmpFeed
 -- alter table #tmpFeed add RowNumber int
 -- alter table #tmpFeed drop column RowNumber  


declare @EachCommentCount int
set @EachCommentCount=3

select * from
(
	SELECT *, Row_Number() 
    OVER (partition by parentkey ORDER BY lastupdatedstamp desc) EachCommentIndex 
	FROM #tmpFeed
) a
where EachCommentIndex <= @EachCommentCount

drop table #tmpFeed

初始化資料截圖:


查詢結果截圖:


請看上圖的EachCommentIndex

(結束)