我必须获取所有订单的所有计数,这些订单已传递给查询,即使是 null 也是如此。我在 SQL Server 2008R2 中开发了这样的查询:
SELECT COUNT(UserId), b.OrderId
FROM @OrderList b
LEFT JOIN
(
SELECT DISTINCT pat_base.UserId, prov_list.OrderId
FROM Users pat_base
LEFT JOIN Assetments hlth_asmt ON hlth_asmt.UserId = pat_base.UserId
AND hlth_asmt.Date BETWEEN @StartDate AND @EndDate
LEFT JOIN Logs proc_log ON proc_log.UserId = pat_base.UserId
AND proc_log.PLDATE BETWEEN @StartDate AND @EndDate
LEFT JOIN Encounter med_enc_log ON med_enc_log.UserId = pat_base.UserId
AND med_enc_log.EncounterDate BETWEEN @StartDate AND @EndDate
LEFT JOIN @OrderList prov_list ON
hlth_asmt.OrderId = prov_list.OrderId
OR proc_log.OrderId = prov_list.OrderId
OR med_enc_log.OrderId = prov_list.OrderId
WHERE hlth_asmt.UserId IS NOT NULL
OR proc_log.UserId IS NOT NULL
OR med_enc_log.UserId IS NOT NULL
) a ON a.OrderId=b.OrderId
GROUP BY b.OrderId
如果我删除加入的子查询,订单将被多对多关系切割。是否可以用连接替换子查询?
PS这是现在的输出:
OrderId
----------- -----------
8 10001
0 10003
没有子查询的输出:
OrderId
----------- -----------
8 10001