简体   繁体   中英

How to use count with Distinct ON

I have this query that already works, i need to write count query for this (need pagination), and i have issues using count with DISTINCT ON, anyone knows correct syntax and way to use it, i already googled but was not able to find any count queries with DISTINCT ON

As result i'm expecting total number of rows from this query that already works

select DISTINCT on (csd.team_contest_id)
        c.id as contestId
            from contest as c
            left join company_sponsor_team as csd on csd.contest_id = c.id
            left join sponsor as s on s.id = c.sponsor_id
            left join team as d on d.id = c.team_id
            left join player as m on c.creator_id = m.id
            WHERE c.id = c.id 
            AND ((c.team_id is not null and c.sponsor_id is null and lower(d.name) LIKE LOWER(CONCAT('%TAN%')))
            OR (c.team_id is not null and c.sponsor_id is not null and lower(s.name) LIKE LOWER(CONCAT('%TAN%')))
            OR (c.team_id is null and lower(s.name) LIKE LOWER(CONCAT('%TAN%')))) AND (CURRENT_DATE < c.archive_date)

If you want to count the number of rows, use a subquery:

select count(*)
from ( <your query here> ) x;

If you have an aversion to subqueries, you can always do:

select count(distinct csd.team_contest_id)
from . . .  <the rest of your query here>;

This returns the same value assuming that csd.team_contest_id is not NULL .

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM