如何在sql中合并其他表中不存在的行?

时间:2015-05-28 09:55:00

标签: sql-server sql-server-2008

我有桌子 的 CL_Client cl_id | cl_name | cl_system 1 | a | Dpo 2 | b | DPO 3 | c | Dpo 4 | d
CLOI_ClientOrderItems

Cl_id|cl_name|orderid|    date      |status |masterid
  1  |   a   | 123   |  27/5/0215   |  12   |  111
  1  |   a   | 123   |  27/5/0215   |  15   |  111
  2  |   b   | 213   |  27/5/0215   |  12   |  222
  3  |   c   | 452   |  27/5/0215   |  16   |  333
  4  |   d   | 458   |  27/5/0215   |  20   |  444
  4  |   d   | 452   |  27/5/0215   |  22   |  333

发票表

orderid|rate|master id|invoice_date
  123  |10  | 111     |27/5/2015
  213  |10  | 222     |27/5/2015
  458  |10  | 444     |27/5/2015
发票表中的

没有masterorderid 333的行,但结果我也想显示它。

我已经尝试过此查询,但它无法正常运行:

SELECT distinct 
    C.cl_id,
    C.cl_name,
    [dbo].getOrderCountbyMasterorderID(CO.masterorderid) as No_Of_Orders,
    CONVERT(VARCHAR(5),CO.cloi_order_date,108) as OrderTime,
    I.in_total,
    CO.MasterOrderId,
    CO.cloi_current_status
from
    dbo.CL_Clients C
    INNER JOIN dbo.CLOI_ClientOrderItems CO
        ON C.cl_id = CO.cl_id 
    LEFT OUTER JOIN dbo.IN_Invoices I
        ON CO.MasterOrderId = I.MasterOrderId
where
    CO.cloi_current_status in(7,8,160,163,167,170,250,251,162) and
    C.cl_system='Dpo' and
    datepart(yyyy,I.in_date_issued)=2015 and
    datepart(mm,I.in_date_issued)=05 and
    datepart(dd,I.in_date_issued)=27
group by
    C.cl_id,
    C.cl_name,
    CO.masterorderid,
    CO.cloi_order_date,
    CO.cloi_current_status,
    I.in_total,
    CO.MasterOrderId 
order by 
    OrderTime

预期结果

cl_id | cl_name |No_Of_Orders|  OrderTime|in_total|MasterOrderId|status
1     |    a    |2       |  09:45    | 65.33  |111          |12       
2     |    b    |1       |  09:53    | 65.33  |222          |15   
3     |    c    |1       |  09:54    | 43.21  |333          |16
4     |    d    |2       |  09:56    | 43.21  |444          |20

1 个答案:

答案 0 :(得分:0)

您尚未显示CL_Clients表的数据。

首先尝试执行此查询

SELECT distinct 
    C.cl_id,
    C.cl_name,
    [dbo].getOrderCountbyMasterorderID(CO.masterorderid) as No_Of_Orders,
    CONVERT(VARCHAR(5),CO.cloi_order_date,108) as OrderTime,
    --I.in_total,
    CO.MasterOrderId,
    CO.cloi_current_status
from
    dbo.CL_Clients C
    INNER JOIN dbo.CLOI_ClientOrderItems CO
        ON C.cl_id = CO.cl_id 
    --LEFT OUTER JOIN dbo.IN_Invoices I
        --ON CO.MasterOrderId = I.MasterOrderId
where
    CO.cloi_current_status in(7,8,160,163,167,170,250,251,162)
     and C.cl_system='Dpo'
     --and datepart(yyyy,I.in_date_issued)=2015
     --and datepart(mm,I.in_date_issued)=05
     --and datepart(dd,I.in_date_issued)=27
group by
    C.cl_id,
    C.cl_name,
    CO.masterorderid,
    CO.cloi_order_date,
    CO.cloi_current_status,
    --I.in_total,
    CO.MasterOrderId 
order by 
    OrderTime

如果此处未显示masterorderid = 333,请检查您的where子句。