如何获得左行仅显示一次的连接

时间:2015-12-24 10:57:08

标签: sql sql-server

我有两个表,TableA和TableB。 TableB有1个TableA记录的多个记录。如果我加入这两个,我得到以下内容: -

SELECT TableA.OrderId, TableA.OrderDate, TableB.Description,TableB.Quantity
from TableA
INNER JOIN on TableA.OrderId = TableB.OrderId

TableA.OrderId | TableA.OrderDate | TableB.Description | TableB.Quantity
1              | 24/12/2015       | Banana             | 10 
1              | 24/12/2015       | Apple              | 5
1              | 24/12/2015       | Pear               | 7
1              | 24/12/2015       | Orange             | 3

有谁知道如何获得以下输出? : -

TableA.OrderId | TableA.OrderDate | TableB.Description | TableB.Quantity
1              | 24/12/2015       | Banana             | 10
                                  | Apple              | 5
                                  | Pear               | 7
                                  | Orange             | 3

许多小时徒劳无功的搜索!

1 个答案:

答案 0 :(得分:0)

检查

create table TableA(OrderId int not null,
OrderDate date null)

insert into TableA Values(1,'12/24/2015')

create table TableB(OrderId int not Null,
Description varchar(50) null,
Quantity int null)

insert into TableB values(1,'Banana',10) 
insert into TableB values(1,'Apple',5)
insert into TableB values(1,'Pear',7)
insert into TableB values(1,'Orange',3)


select case when ttt.RowNum=1 then convert(varchar(50),ttt.OrderId) else '' end,
case when ttt.RowNum=1 then convert(varchar(50),ttt.OrderDate) else '' end,
ttt.Description,
ttt.Quantity
from
(select a.OrderId 
,a.OrderDate
,b.Description,
b.Quantity
,RowNum = ROW_NUMBER() OVER (PARTITION BY a.OrderId ORDER BY 1/0) 
 from TableA a join TableB b on a.OrderId=b.OrderId) as ttt