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中的行。
答案 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