如何删除子查询?

时间:2013-01-18 09:58:12

标签: sql sql-server sql-server-2008 tsql

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

如果我删除已连接的子查询,则会使用多对多关系剪切订单。是否可以用连接替换子查询?

P.S。现在输出:

            OrderId
----------- -----------
8           10001
0           10003

不带子查询的输出:

            OrderId
----------- -----------
8           10001

2 个答案:

答案 0 :(得分: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

中有不一致的数据

答案 1 :(得分:1)

您可以从单个查询返回结果,但我建议不要使用连接。相反,删除外部查询,并更改为内部查询以对计数使用窗口函数。所以你的SELECT子句类似于:

SELECT DISTINCT
   pat_base.UserId,
   prov_list.OrderId,
   COUNT(pat_base.UserId) OVER (PARTITION BY prov_list.OrderId) as UserCount