How to count on DISTINCT ON without subquery

时间:2019-04-17 01:51:52

标签: sql postgresql

I'm trying to implement paging where it gets the last profile with a specific email that hasn't been verified. I don't understand why this query fails with

column "profile.email" must appear in the GROUP BY clause or be used in an aggregate function

select distinct ON (email) email, count(*) 
from "profile" where "verified" = false 
order by "email" asc, "created_date" asc limit 1

but this one works

select distinct ON (email) email, * 
from "profile" where "verified" = false 
order by "email" asc, "created_date" asc limit 10

Is there any way for me to address this without using subqueries?

Edit

After some testing the given answer does not appear to be correct.

select distinct ON (email) email, count(*) over()
from "profile" 
where "email" = 'example@test.com' 
order by "email" desc, "created_date" desc limit 1

returns (incorrect)

[{email: 'example@test.com',count:18 }]

select distinct ON (email) email
from "profile" 
where "email" = 'example@test.com' 
order by "email" desc, "created_date" desc limit 10

returns (correct)

[{email: 'example@test.com'}]

1 个答案:

答案 0 :(得分:2)

You can use a window function:

select distinct ON (email) email, count(*) over ()
from "profile"
where "verified" = false 
order by "email" asc, "created_date" asc
limit 1

For this example, I don't know what advantage that has over:

select email, count(*) over ()
from "profile"
where "verified" = false 
order by "created_date" asc
limit 1