I'm trying to write a query to determine the number of unique users in a table over a rolling window of 30 days.
I figured I'd write something like this
select mydate, count(distinct users)
over (order by mydate rows between 30 preceding and current row);
But this isn't supported in HP Vertica. Is there another way I can re-write the window frame naturally, without using window functions?
Something like this (you will get the idea - use function)
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]
instead DATEDIFF you can use anything you want to get desired results
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.