Postgres:子查询中时间戳的日期分组

时间:2019-02-14 17:47:10

标签: postgresql

我正在尝试找出每天每个列表产生多少线索。

我有这个查询:

SELECT 
    vl.listing_id,
    vl.created_at::date as dt,
    (
        SELECT count(*) 
        FROM voice_leads vl2
        WHERE vl2.listing_id = vl.listing_id 
        AND vl.created_at::date = vl2.created_at::date
    ) as cnt
FROM voice_leads vl
GROUP BY listing_id, vl.created_at::date
ORDER BY listing_id

但是执行时,我收到“错误:子查询从外部查询第8行使用未分组的列“ vl.created_at”:AND vl.created_at :: date = vl2.created_at :: date”

有什么想法我可以解决吗?

2 个答案:

答案 0 :(得分:0)

SELECT 
    vl.listing_id,
    vl.created_at::date as dt,
    count(cnt.*)
FROM voice_leads vl, lateral (SELECT *
        from voice_leads vl2
        WHERE vl2.listing_id = vl.listing_id 
        AND vl.created_at::date = vl2.created_at::date) cnt
GROUP BY vl.listing_id, vl.created_at::date
ORDER BY listing_id

答案 1 :(得分:0)

您不需要子查询:

SELECT 
    vl.listing_id,
    vl.created_at::date as dt,
    count( vl.listing_id ) as cnt
FROM voice_leads vl
GROUP BY listing_id, vl.created_at::date
ORDER BY listing_id

应该做同样的事情。

count(field)将计算每个组中的行数。

count(*)将计算总行数。