SQL GROUP BY:获取索引视图的最新更新记录

时间:2009-07-17 10:10:49

标签: sql-server tsql group-by indexed-view

我正在尝试使用索引视图进行行版本控制,按键和时间戳对记录进行分组,并获取最大(时间戳)记录。这很好,但我使用的查询(请参阅下面的视图)执行自连接,这意味着它不能在索引视图中使用,我认为这对性能至关重要。有没有办法重写查询,以便可以使用SCHEMABINDING成功创建视图?

我正在使用2005年,但2008年唯一的解决方案也没问题。

IF EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[Items]'))
    DROP VIEW [dbo].[Items]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[ItemHistory]') AND type in (N'U'))
    DROP TABLE [dbo].[ItemHistory]
GO
CREATE TABLE [dbo].[ItemHistory](
    [Key] [nchar](10) NOT NULL,
    [Value] [int] NOT NULL,
    [TimeStamp] Timestamp NOT NULL,
    [LastUpdateBy] [varchar](50) NOT NULL CONSTRAINT [DF_ItemHistory_LastUpdateBy]  DEFAULT (SUSER_NAME()),
    [Deleted] BIT NOT NULL DEFAULT (0)
    CONSTRAINT [PK_ItemHistory] PRIMARY KEY CLUSTERED 
    (
        [Key] ASC,
        [TimeStamp] ASC
    ) ON [PRIMARY]
)
GO
CREATE VIEW dbo.Items
--WITH SCHEMABINDING --doesnt work with the query below :(
AS
    SELECT ih.[key], ih.[Value] FROM ItemHistory ih
    INNER JOIN (
        SELECT [Key], Max([TimeStamp]) [TimeStamp]
        FROM ItemHistory
        GROUP BY [Key]
    ) ih2 ON ih.[key] = ih2.[key] AND ih.[TimeStamp] = ih2.[TimeStamp] AND Deleted = 0
GO 
INSERT INTO Items ([Key], [Value]) VALUES ('ItemA', 1)
INSERT INTO Items ([Key], [Value]) VALUES ('ItemA', 2)
INSERT INTO Items ([Key], [Value]) VALUES ('ItemA', 3)

GO
SELECT * FROM ItemHistory
SELECT * FROM Items

1 个答案:

答案 0 :(得分:2)

如果您将ItemHistory替换为dbo.ItemHistory视图定义中的Items,则应该有效。

此外,您可能会发现以下查询的效果更好,因为它可以避免使用MAX函数。

CREATE VIEW dbo.Items
WITH SCHEMABINDING
AS
    SELECT ih.[key], ih.[Value] FROM dbo.ItemHistory ih
    WHERE NOT EXISTS (SELECT [Key]
        FROM dbo.ItemHistory AS ih2
        WHERE ih.[key] = ih2.[key] AND ih.[TimeStamp] < ih2.[TimeStamp]) AND Deleted = 0
GO