POSTGRESQL COUNT()返回更多

时间:2014-06-26 09:31:15

标签: sql postgresql

我有这个SQL语句:

select a.title, a.video_id, b.id
from
    tzrat_community_videos a
    inner join
    tzrat_video_views b on a.video_id = b.videoid
where
    b.cdate >= '2014-01-01 00:00:00' and
    b.cdate <= '2014-06-26 23:59:59' and
    a.video_id = 'dCflt1d2xPw' and
    a.published = 1 and b.duration != 0 and
    (
        (a.percent is not null and (100*b.seconds)/b.duration >= a.percent ) or
        ((100*b.seconds)/b.duration >= 80)
    )
    group by b.videoid, a.title, a.video_id, b.id

结果: http://i.stack.imgur.com/I649X.png

但是我想只有标题,video_id和它出现的次数(我想要这个视频的观看次数) 所以,我发表这样的声明:

select a.title, a.video_id, count(b.id) as views
from
    tzrat_community_videos a
    inner join
    tzrat_video_views b on a.video_id = b.videoid
where
    b.cdate >= '2014-01-01 00:00:00' and
    b.cdate <= '2014-06-26 23:59:59' and
    a.video_id = 'dCflt1d2xPw' and
    a.published = 1 and
    b.duration != 0 and
    (
        (a.percent is not null and (100*b.seconds)/b.duration >= a.percent ) or
        ((100*b.seconds)/b.duration >= 80)
    )
group by b.videoid, a.title, a.video_id

但这让我回答: http://i.stack.imgur.com/fD1zY.png

那么......我做错了什么?是同一个陈述,只是b.id - &gt;将(b.id)计为视图

1 个答案:

答案 0 :(得分:3)

在第一种情况下,您也按b.Id

分组

在第二种情况下你不做什么(当然,因为它在集合函数中)。

所以改变

count(b.id)

通过

count(distinct b.id)

如果您想避免重复b.id次。