最后希望的结果是:在Table1里面增加一列“数量”,此列显示的是比如OfficeID=67在table2和table3中一共有多少条数据;OfficeID=77在table2和table3中一共有多少条数据…
Table1:
Table2:
Table3:
这个不难实现
SELECT officeid , COUNT(*) AS total INTO #temp FROM ( SELECT offceid FROM table2 UNION ALL SELECT offceid FROM table3 ) a GROUP BY offceid SELECT officeid , ( CASE WHEN EXISTS ( SELECT total FROM #temp WHERE officeid = table1.officeid ) THEN ( SELECT total FROM #temp WHERE officeid = table1.officeid ) ELSE 0 END ) AS Total FROM table1 DROP TABLE #temp