-4

我有两张桌子

Table1                               Table2
id     Name                     id   table1id      Name
1       A                        1     1            a
2       B                        2     1            aa
3       C                        3     1            aaa
                                 4     2            b
                                 5     2            bb

我想输出为 Name1 Name2

A          a
           aa
           aaa
B          b
           bb
4

1 回答 1

1

尝试这个 :

Declare @Table1 table
(id int ,name varchar(10))

Insert into @Table1
values
(1,'A' ),
(2,'B'),
(3,'C' )


Declare @Table2 table
(id int,tableid int ,name varchar(10))

Insert into @Table2
values
(2, 1,'aa'),
(3, 1,'aaa'),
(4, 2 ,'b'),
(5,2,'bb')


;With cte(Name1,Name2,rn) as
(Select t1.name ,t2.name,
  row_number() over ( partition by t1.name order by  t1.id) as rn 
  from @table1 as t1 inner join @Table2 as T2
  on t2.tableid=t1.id
)
Select case when rn=1 then name1 else '' end as c1,
name2
from cte
于 2013-03-15T12:19:24.570 回答