多个联接计数不会为0

时间:2017-05-29 07:56:01

标签: sql oracle join

我一直在尝试使用连接来获取数据。但问题是结果没有第二或第三表中没有数据的记录。 这是查询;

SELECT AUDIT_CONFIG.TITLE,AUDIT_CONFIG.AUDITOR_POOL,AUDIT_CONFIG.FREQUENCE,
TO_CHAR(TO_DATE(AUDIT_CONFIG.START_DATE,'yyyymmdd'),'dd/mm/yyyy') AS "START", 
AUDIT_CONFIG.AUDIT_ID, TO_CHAR(MAX(AUDIT_DATES.AUDIT_DATE), 'dd/mm/yyyy') AS "FINISH", 
TRUNC(MAX(AUDIT_DATES.AUDIT_DATE) - SYSDATE) DAY_TO,
(SELECT COUNT(DISTINCT UNIQ_ID) FROM SENDED_AUDIT) AS SCHEDULED,
(SELECT COUNT(*) FROM AUDIT_RESULTS WHERE PASSORFAIL='P') AS PASS,
(SELECT COUNT(*) FROM AUDIT_RESULTS WHERE PASSORFAIL='F') AS FAIL

FROM AUDIT_CONFIG                                      
RIGHT JOIN AUDIT_DATES ON AUDIT_DATES.AUDIT_ID = AUDIT_CONFIG.AUDIT_ID 
RIGHT JOIN SENDED_AUDIT ON SENDED_AUDIT.AUDIT_ID=AUDIT_CONFIG.AUDIT_ID
RIGHT JOIN AUDIT_RESULTS ON AUDIT_RESULTS.AUDIT_ID=AUDIT_CONFIG.AUDIT_ID

GROUP BY AUDIT_CONFIG.TITLE, AUDIT_CONFIG.AUDITOR_POOL, AUDIT_CONFIG.FREQUENCE, 
TO_CHAR(TO_DATE(AUDIT_CONFIG.START_DATE, 'yyyymmdd'), 'dd/mm/yyyy'), AUDIT_CONFIG.AUDIT_ID;

这是一个理解问题的图像; (我的查询只返回第一行)

what i want

那么获得0行的建议是什么?提前谢谢..

EDİT对于Thorsten Kettner: 现在解决了:)谢谢你的帮助和时间

1 个答案:

答案 0 :(得分:0)

您的查询看起来过于复杂

  • 首先:很少有人使用右外连接,因为我们发现它们比左外连接更不直观。它甚至看起来你对连接感到困惑,并且真的想要左连接instad。
  • 另一件事是count子查询与主查询中的记录无关。我不认为这是故意的,不是吗?
  • 然后您加入sended_auditaudit_results - 您在计数子查询中使用的相同表格,但您不会在查询中使用这些已加入的记录。

我想你想要:

select 
  ac.title,
  ac.auditor_pool,
  ac.frequence,
  to_char(to_date(ac.start_date, 'yyyymmdd'), 'dd/mm/yyyy') as "start", 
  ac.audit_id,
  to_char(ad.max_date, 'dd/mm/yyyy') as "finish", 
  trunc(ad.max_date - sysdate) as day_to,
  sa.scheduled,
  nvl(ar.pass, 0) as pass,
  nvl(ar.fail, 0) as fail
from audit_config ac
left join
(
  select audit_id, max(audit_date) as max_date
  from audit_dates
  group by audit_id
) ad on ad.audit_id = ac.audit_id
left join
(
  select audit_id, count(distinct uniq_id) as scheduled
  from sended_audit
  group by audit_id
) sa on sa.audit_id = ac.audit_id
left join
(
  select 
    audit_id, 
    count(case when passorfail = 'p' then 1 end) as pass,
    count(case when passorfail = 'f' then 1 end) as fail
  from audit_results
  group by audit_id
) ar on ar.audit_id = ac.audit_id;