I'm using PostgreSQL in SQLWorkbenchJ and I'm struggling.
I have a WITH
statement that selects a date depending on its row number. If the statement cannot find the row number, I want to select null in the date field. This currently doesn't happen, it just selects records where all fields are not null. I'm assuming it is to do with joins but I'm not sure.
The current statement is below. It should return around 50,000 records but it currently returning just under 2000.
WITH FifthEnquiry AS
(
SELECT emailaddress,
SentDate,
ROW_NUMBER() OVER (PARTITION BY emailaddress ORDER BY COUNT(*) DESC) AS rk
FROM SentEmails
GROUP BY emailaddress,
SentDate
),
TenthEnquiry AS
(
SELECT emailaddress,
SentDate,
ROW_NUMBER() OVER (PARTITION BY emailaddress ORDER BY COUNT(*) DESC) AS rk
FROM SentEmails
GROUP BY emailaddress,
SentDate
),
TwentiethEnquiry AS
(
SELECT emailaddress,
SentDate,
ROW_NUMBER() OVER (PARTITION BY emailaddress ORDER BY COUNT(*) DESC) AS rk
FROM SentEmails
GROUP BY emailaddress,
SentDate
)
SELECT FifthEnquiry.emailaddress,
FifthEnquiry.SentDate AS Fith,
TenthEnquiry.SentDate AS Tenth,
TwentiethEnquiry.SentDate AS Twentieth,
FROM FifthEnquiry
JOIN TenthEnquiry ON FifthEnquiry.emailaddress = TenthEnquiry.emailaddress
JOIN TwentiethEnquiry ON FifthEnquiry.emailaddress = TwentiethEnquiry.emailaddress
WHERE (FifthEnquiry.rk = 5)
AND (TenthEnquiry.rk = 10)
AND (TwentiethEnquiry.rk = 20)