在SQL中加入两个表

时间:2017-04-21 07:44:43

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

我正在寻找一种从表Table1和Table2生成结果的解决方案。请参阅下面的图片了解详情

enter image description here

Table1.OrderID = Table2.OrderID

我不是在寻找简单的连接查询。在输出Table1中值不重复。

3 个答案:

答案 0 :(得分:2)

select Table1.*, Table2.Items, Table2.Quantity -- List the columns you want. I've specified the table name to avoid ambiguous column errors, and * means all columns
from Table1
inner join Table2 -- This is a join (inner gets only the records that exist in both tables)
on Table1.OrderID = Table2.OrderID -- This is the join condition, you define which columns are the same between the tables

对于空白位,因为你缺乏在显示层处理它的意义:

with CTE as
(
select Table1.*, 
       Table2.Items, 
       Table2.Quantity,
       row_number() over(partition by Table1.OrderID order by Items ) as rn
    from Table1
    inner join Table2 
    on Table1.OrderID = Table2.OrderID 
)

select case when rn = 1 then OrderID end as OrderID,
       case when rn = 1 then CustomerName end as CustomerName ,
       case when rn = 1 then CTE.Desc end as Desc,
       Items,
       Quantity
from CTE

答案 1 :(得分:1)

最后我找到了一个我正在寻找的解决方案

WITH MasterTable as (SELECT ROW_NUMBER() OVER(PARTITION BY OrderID ORDER BY OrderID ASC) AS SlNo,* FROM Table1),
DetailTable as (SELECT ROW_NUMBER() OVER(PARTITION BY OrderID ORDER BY OrderID ASC) AS SlNo,* FROM Table2)

SELECT * FROM MasterTable A FULL JOIN DetailTable B
ON A.OrderID = B.OrderID AND A.SlNo=B.SlNo
ORDER BY B.OrderID

答案 2 :(得分:0)

您可以使用 ROW_NUMBER()OVER(PARTITION BY ORDER BY)来实现此结果 代码:

select 
    CASE WHEN ROW_NUMBER() OVER(PARTITION BY tb1.orderid ORDER BY tb1.orderid) = 1 THEN tb1.orderid ELSE null END AS orderid,
    CASE WHEN ROW_NUMBER() OVER(PARTITION BY tb1.custname ORDER BY tb1.orderid) = 1 THEN tb1.custname ELSE '' END AS custname,
    CASE WHEN ROW_NUMBER() OVER(PARTITION BY tb1.Descp ORDER BY tb1.orderid) = 1 THEN tb1.Descp ELSE '' END AS Descp,
    tb2.item,tb2.quentity
    from tb1 inner join tb2 on tb1.orderid=tb2.orderid

输出:

orderid custname    Descp   item    quentity
   1    Ccustomer1  1item   Pen     1
   2    Ccustomer2  2item   Ball    2
                             Bat    1
   3    Ccustomer3  3item   Book    2
                            Box     1
                            Bag     1
                            Pen     2