0

我必须获取所有订单的所有计数,这些订单已传递给查询,即使是 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
4

2 回答 2

1

你必须改变

LEFT JOIN @OrderList prov_list ON

RIGHT JOIN @OrderList prov_list ON

如果您使用左连接,您会过滤掉 @OrderList 中但没有预期用户的订单

所以查询就像

SELECT COUNT(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
    RIGHT 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
group by prov_list.OrderId

编辑

是的,这意味着这些行在 where 子句中被过滤掉了

将其更改为

WHERE hlth_asmt.UserId IS NOT NULL
OR proc_log.UserId IS NOT NULL
OR med_enc_log.UserId IS NOT NULL
OR pat_base IS NULL

但我认为这意味着您在 db 中有不一致的数据

于 2013-01-18T10:07:35.690 回答
1

You can return the result from a single query, but I'd recommend not using a join. Instead, remove your outer query, and change to inner query to use a windowing function on the count. So your SELECT clause would be something similar to:

SELECT DISTINCT
   pat_base.UserId,
   prov_list.OrderId,
   COUNT(pat_base.UserId) OVER (PARTITION BY prov_list.OrderId) as UserCount
于 2013-01-18T10:12:44.107 回答