我有一张名为customer,hobby的表。 顾客有几个爱好。所以,如果我和表爱好者一起加入我的桌面客户,我会得到如下结果:
[CustomerName] [HobbyName]
Harry Tennis
Harry Football
我希望看到这样的结果:
[CustomerName] [HobbyName1] [HobbyName2]
Harry Tennis Football
我当前的查询如下所示:
Select tCustomer.name, tHobby.name
from dbo.customer tCustomer
inner join dbo.hobby tHobby on tHobby.customerid = tCustomer.id
答案 0 :(得分:6)
您没有提供有关表结构的许多详细信息,但您可以使用PIVOT获取最终结果,但为了使用它,您首先要使用row_number()
为每个爱好生成一个唯一的序列每个客户:
select customer, Hobby1, Hobby2
from
(
Select c.name customer,
h.name hobby,
'Hobby'+
cast(row_number() over(partition by c.id
order by h.name) as varchar(10)) seq
from dbo.customer c
inner join dbo.hobby h
on h.customerid = c.id
) d
pivot
(
max(hobby)
for seq in (hobby1, Hobby2)
) piv;
见SQL Fiddle with Demo。如果您不想使用PIVOT函数,那么您还可以使用CASE表达式和聚合函数:
select customer,
max(case when seq = 1 then hobby end) hobby1,
max(case when seq = 2 then hobby end) hobby2
from
(
Select c.name customer,
h.name hobby,
row_number() over(partition by c.id
order by h.name) seq
from dbo.customer c
inner join dbo.hobby h
on h.customerid = c.id
) d
group by customer;