SQL表联接查找匹配数据

时间:2018-12-05 14:16:16

标签: sql-server

我们从事医疗保健业务,我们有一个SQL数据库,用于存储指示(客户应在几分钟之内收到多少护理)和约会(我们在几分钟内可以为客户提供多少护理)的信息。

我写的查询如下:

SELECT

CF.ClientNr,
C.Name,
F.Description AS Function,
CF.Time AS Indication,
SUM(P.Minutes) As Production,
C.Insurance,
V.Name AS Team

FROM ClientFunctie AS CF

INNER JOIN Client AS C ON C.ClientNr=CF.ClientNr
INNER JOIN HoofdaanbiederFunctie AS H ON CF.HoofdaanbiederFunctieNr=H.HoofdaanbiederFunctieNr
INNER JOIN Functie AS F ON H.FunctieNr=F.FunctieNr

LEFT JOIN Planning AS P ON CF.ClientFunctieNr=P.ClientFunctieNr
LEFT JOIN DeclaratieAfhandeling AS D ON P.DeclaratieAfhandelingNr=D.DeclaratieAfhandelingNr
LEFT JOIN Vestiging AS V ON P.VestigingNr=V.VestigingNr

WHERE 

D.StatusNr = 2 AND
CF.Einddatum > '2018-01-01' /*startdatum*/ AND
CF.Startdatum < '2018-01-28' /*einddatum*/ AND
CF.IsAkkoord = 1 AND
F.Omschrijving LIKE '%mwa%' AND
F.Omschrijving LIKE '%hv%'

GROUP BY

CF.ClientNr,
C.Name,
F.Description AS Function,
CF.Time AS Indication,
C.Insurance,
V.Name AS Team

我的目标是知道每个指示已发送了多少分钟,而0分钟已接收了多少指示。

现在,我只在带有分钟数的结果中看到指示,但我也想查看具有0分钟的指示。我尝试过左/右联接,但我现在没有选择。我真的很感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

没有表结构会有点困难,但是我通常会这样。

我想我会在子查询中提取计算结果,然后编辑主查询,诸如此类:

SELECT CF.ClientNr,
C.Name,
F.Description AS Function,
CF.Time AS Indication,
WL-Production As Production,
C.Insurance,
V.Name AS Team

FROM [...]
LEFT JOIN ( SELECT SUM(P.Minutes) As Production, CF.ClientNr as ClientNr 

FROM ClientFunctie AS CF
INNER JOIN Planning AS P ON CF.ClientFunctieNr = P.ClientFunctieNr
INNER JOIN DeclaratieAfhandeling AS D ON P.DeclaratieAfhandelingNr = D.DeclaratieAfhandelingNr

WHERE D.StatusNr = 2
GROUP BY CF.ClientNr) AS WL ON CF.ClientFunctieNr = WL.ClientNr 

(我没有SqlServer对其进行测试,希望会有帮助)

您可以使用相同的方法来计数0分钟指示。

还要查看您的查询,您似乎还需要完成该工作的需求团队的名称,如果您需要总时间,则无论哪个团队进行了工作,您的查询都可能需要进行一些调整。