查询用户发布条目次数的最佳方法

Optimal method to query number of times a user has an posted an entry

我有一个 table 例如,

Column     |   Type
id            integer
job_id        integer
user_id       integer
date_posted  datetime

我想编写一个查询来分解发布一次职位的用户数量与多次发布至少一个职位的用户数量

    with user_jobs as (
                 select user_id, job_id, count(distinct date_posted) as num_posted
                 from table
                 group by user_id, job_id
                 )

Select SUM(Case when avg_num_posted > 1 then 1 end) as posted_multiple_times,
       SUM(Case when avg_num_posted = 1 then 1 end) as posted_once
FROM(
    Select user_id, avg(num_posted) as avg_num_posted
    from user_jobs
    Group by user_id) t

这给了我输出,但想知道是否有更优化的方法,谢谢!

如果我没理解错的话,您可以将不同作业的数量与 job/date 组合的数量进行比较。让我假设一份工作绝不会在同一日期发布两次。如果是这样的话:

Select sum(case when num_listings > num_jobs then 1 end) as posted_multiple_times,
       sum(case when num_listings = num_jobs then 1 end) as posted_once
from (select user_id, count(*) as num_listings, count(distinct job_id) as num_jobs
      from t
      group by user_id
     ) u;

如果职位可以在一天内发布两次并且您不想将其计为重复,那么一种方法是:

Select sum(case when num_listings > num_jobs then 1 end) as posted_multiple_times,
       sum(case when num_listings = num_jobs then 1 end) as posted_once
from (select user_id, count(*) as num_listings,
             count(distinct job_id) as num_jobs
      from (select distinct user_id, job_id, date_posted from t) t
      group by user_id
     ) u;