使用另一个查询的结果进行查询

时间:2016-01-21 13:47:48

标签: sql join oracle10g

我尝试编写一个查询,根据另一个查询的结果生成一组结果。查询的所有必需数据来自一个表,只是一组不同的查询条件。我不确定我所询问的内容是否可以在单个查询中创建。

select OBJID, case_type, activity, TITLE, x_rev_esc_prim_reason, x_rev_esc_sec_reason, x_esc_third_reason, x_create_dt, x_update_dt, x_sales_rep 
    from table_case

上述查询的结果基本上从表中捕获了我需要的所有内容,但我需要减少数量或过滤返回的结果。

以下查询的结果是我需要的,以进一步减少上述查询的结果。此外,查询还需要以下查询结果中的x_create_dt大于上述查询结果的结果中的x_create_dt。

select OBJID, case_type, activity, TITLE, x_rev_esc_prim_reason, x_rev_esc_sec_reason, x_esc_third_reason, x_create_dt, x_update_dt, x_sales_rep 
    from table_case
    where case_type = 'Sales'
    and activity = 'DO'  

IMAGE OF THE SAMPLE DATA AND RESULTS

DB目前是Oracle10g

1 个答案:

答案 0 :(得分:0)

您希望为每个case_type='request'返回所有sales_rep行,其中x_create_date早于x_create_date行中的case_type='Sales' and activity='DO'sales_rep

首先,我们创建返回限定信息的查询:

SELECT sales_rep, MAX(x_create_date) AS latest_date
FROM table_case
WHERE case_type = 'Sales' 
  AND activity = 'DO'
GROUP BY sales_rep

您可以单独测试此查询,并验证它是否产生了所需的结果。

然后我们在外部查询中嵌入此查询,并加入这两个,如下所示:

SELECT c.OBJID, c.case_type, c.activity, c.TITLE, 
    c.x_rev_esc_prim_reason, c.x_rev_esc_sec_reason, c.X_esc_third_reason, 
    c.x_create_dt, c.x_update_dt 
FROM table_case AS c
INNER JOIN (
    SELECT sales_rep, MAX(x_create_date) AS latest_date
    FROM table_case
    WHERE case_type = 'Sales' 
      AND activity = 'DO'
    GROUP BY sales_rep) AS q
ON c.sales_rep = q.sales_rep and q.latest_date > c.x_create_date
WHERE c.case_type = 'request'
相关问题