【问题标题】:inner join with group by and finding count of repeated values in a column与 group by 进行内部连接并查找列中重复值的计数
【发布时间】:2021-09-25 17:25:52
【问题描述】:

我正在使用 PostgreSQL 数据库。

我有表jobjob_applicationinterview,它们的结构如下:

工作表:

select * from job;

job_application

select * from job_application;

采访表:

select * from interview;

我已经准备了一个查询,通过加入上面的表格来获取一些数据,如下所示(当然,我的实际需求略有不同,稍后我会解释):

SELECT job_description,
       i1.interview_type,
       hired,
       open_positions - hired   AS remaining,
       Count(i1.interview_type) AS current_count
FROM   job
       INNER JOIN job_application j1
               ON job.id = j1.job_id
       INNER JOIN interview i1
               ON j1.id = i1.jobapplication_id
GROUP  BY i1.interview_type,
          job_description,
          hired,
          open_positions; 

上述查询将产生如下数据:

但我的实际要求是针对job_description 获取每个interview_type(L1、L2、HR 等...来自interview 表)的计数。 例如如下所示:

谁能指导/解释我如何从我已经准备好的查询中获取上述格式的数据?如果您需要任何信息,请告诉我。

【问题讨论】:

    标签: sql database postgresql


    【解决方案1】:

    您可能对 CrossTab (PostgreSQL Crosstab Query) 有一些运气。

    但我没有使用它就到达那里:

    SELECT 
        job.job_description
        ,job.hired
        ,job.open_positions - job.hired AS remaining
        ,COALESCE(L1.cnt, 0) AS L1
        ,COALESCE(L2.cnt, 0) AS L2
        ,COALESCE(HR.cnt, 0) AS HR
        ,COALESCE(EXECUTIVE.cnt, 0) AS EXECUTIVE
    FROM job
    
    LEFT JOIN
    (
    SELECT
        ja.job_id
        ,COUNT(*) AS cnt
    FROM job_application ja
    
    INNER JOIN interview i1
    ON ja.id = i1.jobapplication_id
        
    WHERE i1.interview_type = 'L1'
    
    GROUP BY
        ja.job_id
    ) AS L1
    ON L1.job_id = job.id
    
    LEFT JOIN
    (
    SELECT
        ja.job_id
        ,COUNT(*) AS cnt
    FROM job_application ja
    
    INNER JOIN interview i1
    ON ja.id = i1.jobapplication_id
        
    WHERE i1.interview_type = 'L2'
    
    GROUP BY
        ja.job_id
    ) AS L2
    ON L2.job_id = job.id
    
    LEFT JOIN
    (
    SELECT
        ja.job_id
        ,COUNT(*) AS cnt
    FROM job_application ja
    
    INNER JOIN interview i1
    ON ja.id = i1.jobapplication_id
        
    WHERE i1.interview_type = 'HR'
    
    GROUP BY
        ja.job_id
    ) AS HR
    ON HR.job_id = job.id
    
    LEFT JOIN
    (
    SELECT
        ja.job_id
        ,COUNT(*) AS cnt
    FROM job_application ja
    
    INNER JOIN interview i1
    ON ja.id = i1.jobapplication_id
        
    WHERE i1.interview_type = 'EXECUTIVE'
    
    GROUP BY
        ja.job_id
    ) AS EXECUTIVE
    ON EXECUTIVE.job_id = job.id;
    

    换句话说,对 Job_application 和面试表的 SQL 查询进行连接,并过滤到每种面试类型(如果有更多的面试类型,则不建议这样做)。

    【讨论】:

      猜你喜欢
      • 2013-01-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-30
      • 2020-01-19
      • 2013-01-08
      • 2013-02-15
      相关资源
      最近更新 更多