更改查询以返回不匹配的行

时间:2011-03-12 08:50:27

标签: sql-server-2005 tsql select join

SELECT
  T.clinic_code, C.dt, T.schedule_time, T.section_name,
  T.section_content, CS.schedule_event_source_id
FROM Master_Templates T
  INNER JOIN Calendar C
    ON  T.dw = C.dw
    AND T.mo = (C.D - 1) / 7 + 1
    AND C.Y = '2014'
    AND C.M = '3'
    AND T.clinic_code = 'ABC'
  LEFT OUTER JOIN Clinic_Schedule CS
    ON  CS.schedule_date=convert(varchar, C.dt, 121)
    AND CS.clinic_code=T.clinic_code
    AND CS.schedule_time=T.schedule_time
    AND CS.section_name = T.section_name
  WHERE CS.schedule_event_source_id = 2

Clinic_Schedule包含1条记录:

  

clinic_code | schedule_date | schedule_time | section_name | schedule_event_source_id ABC | 2014-03-03 |上午|学院| 2

Master_Template包含168条记录:

  

clinic_code | dw |莫| schedule_time | section_name | section_content

日历包含用于连接Master_Template记录的列和一周中的几天。

如何更改上面的查询以返回167行?即master_template中的总行数减去了clin_schedule中的行。

2 个答案:

答案 0 :(得分:1)

这个怎么样:

SELECT
  T.clinic_code, C.dt, T.schedule_time, T.section_name,
  T.section_content, CS.schedule_event_source_id
FROM Master_Templates T
  INNER JOIN Calendar C
    ON  T.dw = C.dw
    AND T.mo = (C.D - 1) / 7 + 1
    AND C.Y = '2014'
    AND C.M = '3'
    AND T.clinic_code = 'ABC'
  LEFT OUTER JOIN Clinic_Schedule CS
    ON  CS.schedule_date=convert(varchar, C.dt, 121)
    AND CS.clinic_code=T.clinic_code
    AND CS.schedule_time=T.schedule_time
    AND CS.section_name = T.section_name
    AND CS.schedule_event_source_id = 2
  WHERE CS.clinic_code IS NULL

答案 1 :(得分:0)

要仅返回T中没有CS匹配的记录,您可以使用HAVING,类似于WHERE,但会对JOIN的结果应用条件

SELECT
  T.clinic_code, C.dt, T.schedule_time, T.section_name,
  T.section_content, CS.schedule_event_source_id
FROM Master_Templates T
INNER JOIN Calendar C
    ON  T.dw = C.dw
    AND T.mo = (C.D - 1) / 7 + 1
    AND C.Y = '2014'
    AND C.M = '3'
    AND T.clinic_code = 'ABC'
LEFT OUTER JOIN Clinic_Schedule CS
    ON  CS.schedule_date=convert(varchar, C.dt, 121)
    AND CS.clinic_code=T.clinic_code
    AND CS.schedule_time=T.schedule_time
    AND CS.section_name = T.section_name
    AND CS.schedule_event_source_id = 2
HAVING CS.clinic_code IS NULL