加入3个表空

时间:2016-08-03 02:47:49

标签: sql-server join

有人可以帮忙吗?我是脚本上的菜鸟..下面的脚本(没有BOLDED部分给我空结果)如果我包含BOLDED部分,它会告诉我太多的值。

实际上对于粗体部分,我想要的是从三个不同的表中提取。

表A (OR_ORDER)它由

组成
    ID | CLASS | FACILITY | SOURCE_TYPE | SOURCE_CODE 
    101     IP       XY         N            W010
    102     IP       XY         N            W023 
    103     OP       SX         C            E122 
    114     OP       XY         C            R123

表D (IP_NURSING_UNIT)它由

组成
NURSING_UNIT_CODE | SOURCE_TYPE | LONG_DESC
W010                     N         Ward 10
W023                     N         Ward 23

表H (OP_CLINIC)它由

组成
CLINIC_CODE | SOURCE_TYPE | LONG_DESC
E122              C         Eye Clinic
R123              C         Dental

我希望预期的输出如下所示。只需添加long_desc列...取决于source_type。如果source_type是N,那么它应该从表D中提取数据..如果source_type是C,那么它应该从表H中提取数据。但我不知道如何加入它们。

ID | CLASS | FACILITY | SOURCE_TYPE | SOURCE_CODE | LONG_DESC
101     IP       XY         N            W010        Ward 10
102     IP       XY         N            W023        Ward 23
103     OP       SX         C            E122        Eye Clinic
114     OP       XY         C            R123        Dental

查询:

SELECT 
    A.ID, A.CLASS, C.FACILITY_NAME, A.SOURCE_TYPE,
    (SELECT a.source_code, d.LONG_DESC 
     FROM OR_ORDER A 
     INNER JOIN IP_NURSING_UNIT D ON a.source_code = d.nursing_unit_code 
     INNER JOIN OP_CLINIC H ON a.source_code = h.clinic_code),
    B.ORDER_ID, B.ORDER_CATALOG_CODE, B.CATALOG_DESC,
    B.START_DATE_TIME, B.END_DATE_TIME, B.ORDER_QTY,
    F.LONG_DESC, G.PUBLIC_PRICE, E.PRACTITIONER_NAME
FROM 
    OR_ORDER A, OR_ORDER_LINE B, SM_FACILITY_PARAM C, 
    IP_NURSING_UNIT D, AM_PRACTITIONER E, AM_UOM F, 
    BL_ST_ITEM_BY_PERIOD  G, OP_CLINIC H
WHERE   
    A.CLASS = 'OP'    
    AND A.ORDER_ID = B.ORDER_ID    
    AND A.ORDERING_FACILITY_ID = C.FACILITY_ID     
    AND A.ORDERING_FACILITY_ID = D.FACILITY_ID     
    AND A.ORDERING_FACILITY_ID = H.FACILITY_ID     
    AND A.SOURCE_CODE = D.NURSING_UNIT_CODE     
    AND A.SOURCE_CODE =H.CLINIC_CODE     
    AND B.ORD_PRACT_ID = E.PRACTITIONER_ID     
    AND (G.item_code = B.ORDER_CATALOG_CODE  
    AND G.OPERATING_FACILITY_ID = 'RP'  AND G.EFFECTIVE_TO_DATE IS NULL)
    AND B.ORDER_UOM = F.UOM_CODE AND B.ORD_DATE_TIME BETWEEN TO_DATE('05/02/2016 08:20:00', 'MM/DD/YYYY HH24:MI:SS') AND

TO_DATE(' 05/02/2016 08:30:00',' MM / DD / YYYY HH24:MI:SS')     订购         B.ORD_PRACT_ID

非常感谢任何帮助。提前致谢

1 个答案:

答案 0 :(得分:2)

您似乎想要theToolBar.Realize()

left join

您的查询过于复杂。此外,它不使用正确的显式select o.*, coalesce(nu.long_desc, c.long_desc) as long_desc from or_order o left join ip_nursing_unit nu on o.source_code = nu.source_code and o.source_type = nu.source_type left join op_clinic c on o.source_code = c.source_code and o.source_type = c.source_type; 语法。简单规则:从不JOIN子句中使用逗号。 始终使用正确的FROM语法。

您可能还有其他条件要添加到查询中。