如何使用Distinct ON计数

时间:2018-01-07 20:46:03

标签: sql database postgresql

我有这个查询已经有效,我需要为此编写计数查询(需要分页),我有使用DISTINCT ON计数的问题,任何人都知道正确的语法和使用它的方式,我已经google了但是没有能够使用DISTINCT ON

查找任何计数查询

因此,我希望此查询中已经有效的行总数

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)

1 个答案:

答案 0 :(得分:2)

如果要计算行数,请使用子查询:

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

如果您厌恶子查询,您可以随时执行:

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

假设csd.team_contest_id不是NULL,则返回相同的值。