用窗框计算不同的窗口函数

时间:2015-09-01 05:51:05

标签: sql function window

我正在尝试编写一个查询,以确定30天滚动窗口中表中唯一用户的数量。

我想我会写这样的东西

select mydate, count(distinct users) 
over (order by mydate rows between 30 preceding and current row);

但HP Vertica不支持此功能。有没有其他方法可以自然地重写窗口框架而不使用窗口函数?

1 个答案:

答案 0 :(得分:0)

这样的事情(你会得到这个想法 - 使用功能)

IF OBJECT_ID('[dbo].[MyUser]') IS NOT NULL
    DROP TABLE [dbo].[MyUser]

CREATE TABLE [dbo].[MyUser](    
    [Id] [int] IDENTITY(1,1) NOT FOR REPLICATION NOT NULL,
    MyDate DATETIME NOT NULL,
    Users INT NOT NULL
 CONSTRAINT [PK_MyUser] PRIMARY KEY CLUSTERED 
(
    [Id] ASC
)
)

GO

INSERT INTO [dbo].[MyUser] (MyDate, Users) 
SELECT DATEADD(DAY, -1, GETDATE()), 1
UNION ALL
SELECT DATEADD(DAY, -2, GETDATE()), 2
UNION ALL
SELECT DATEADD(DAY, -3, GETDATE()), 3
UNION ALL
SELECT DATEADD(DAY, -4, GETDATE()), 4
UNION ALL
SELECT DATEADD(DAY, -5, GETDATE()), 5
UNION ALL
SELECT DATEADD(DAY, -6, GETDATE()), 6
UNION ALL
SELECT DATEADD(DAY, -7, GETDATE()), 7
UNION ALL
SELECT DATEADD(DAY, -8, GETDATE()), 8
UNION ALL
SELECT DATEADD(DAY, -9, GETDATE()), 9
UNION ALL
SELECT DATEADD(DAY, -10, GETDATE()), 10

GO

IF OBJECT_ID (N'dbo.GetDistinctUsers', N'FN') IS NOT NULL
    DROP FUNCTION dbo.GetDistinctUsers;
GO

CREATE FUNCTION GetDistinctUsers (@StartDate DATETIME, @DateWindowSizeInDays INT)
RETURNS INT
WITH EXECUTE AS CALLER
AS
BEGIN
DECLARE @Users int;
SELECT @Users = COUNT(DISTINCT Users) FROM [dbo].[MyUser] WHERE DATEDIFF(DAY, @StartDate, MyDate) < @DateWindowSizeInDays
RETURN @Users 
END;
GO

select MyDate, dbo.GetDistinctUsers(MyDate, 2) FROM [MyUser]

而是DATEDIFF你可以使用你想要的任何结果