sql查询在join或subquery的帮助下返回输出

时间:2013-03-15 12:13:34

标签: sql sql-server

我有两张桌子

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

1 个答案:

答案 0 :(得分: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