将两个表与一个表中的其他字段联接

时间:2019-03-04 14:49:09

标签: sql sql-server tsql join

我想将两个表与其他列连接在一起。

第一张表列出了按产品发货的产品数量

`SELECT  case when type=0 then Name else null end report_type, 
    case when type=1 then Name else null end account_level_1, 
    case when type=2 then Name else null end account_level_2,
    case when type=3 then Name else null end account_level_3,
    case when type=4 then Name else null end account_level_4,
    case when type=5 then Name else null end account_level_5
from [dbo].[Account]`

第二张表用于按产品退货的产品数量,还按退货原因增加一列

** Table 1 - Despatches **      
Month   ProductID   No_despatched
Jan     abc          10
Jan     def          15
Jan     xyz          12

我想加入表格以显示退货并在同一行上发货,如果同一产品有多个退货原因,则发货的数量将重复。

** Table 2 - Returns **     
Month   ProductID   No_returned  Return_reason
Jan     abc          2             Too big
Jan     abc          3             Too small
Jan     xyz          1            Wrong colour

希望这很有道理...

谢谢!

afk

3 个答案:

答案 0 :(得分:2)

这似乎是基本的JOIN

select r.month, r.productid, d.no_despathed, r.no_returned, r.return_reason
from returns r join
     despatches d
     on r.month = d.month and r.productid = d.productid;

结果似乎并不是特别有用,因为缺少某些产品(没有退货的产品)。如果返回记录不止一个,则金额会重复。

答案 1 :(得分:0)

只使用连接

  select a.*,b.No_returned,.Return_reason from
   table1 join table2 on a.ProductID=b.ProductID 
                            and a.month=b.month

如果重复,则可以使用distinct

答案 2 :(得分:0)

更改问题中子句的顺序会产生结果。

  

带有其他列。

SELECT Table1.Month, Table1.ProductID, Table1.NoDespatched, Table2.NoReturned, Table2.ReturnReason
  

联接两个表

FROM Table1 LEFT JOIN Table2 
  ON Table1.Month=Table2.Month AND Table1.ProductID=Table2.ProductID

我们使用LEFT JOIN是因为,假定可以在不退货的情况下分派产品,但是没有人可以退还您未发送的产品。

相关问题