查询将多个列合并为1

时间:2013-12-01 22:46:32

标签: sql sql-server

我们有一个数据库查询,可以查询我们网站上的所有产品。 它目前有10,000种产品,其中一些产品属于3类产品,类别信息存储在跟踪表中。

这意味着我们的查询将返回这些产品的3个实例。

我想知道的是什么。是否可以查询数据库并返回这些产品的单个实例,但是将类别名称放在一个列中,如列表?

这被称为聚合函数吗?或者这是某种子查询,它将信息合并为一列供使用。

我们正在使用MSSQL 2012

table products

id
product_name
display_name


table tracking
id
product_id
category_id
view_order


table categories
category_id
category_name


red tshirt with an id 1

categories
Mens Wear  with id of 1
Tshirts    with id of 2
clothing   with id of 3

我们想要的输出是什么

Product_name         category
Red Tshirt           Mens Wear,Tshirts,Clothing

而不是

Product_name         category 
Red Tshirt           Mens Wear
Red Tshirt           Tshirts
Red Tshirt           clothing

这就是我们现在得到的

1 个答案:

答案 0 :(得分:0)

使用For XML技巧创建CSV字段的以下TSQL将起到作用

with combined (product_name, category) as (
  select product_name, category_name
  from
  products 
  inner join tracking on products.id = tracking.product_id
  inner join categories on categories.id = tracking.category_id
)
select
product_name,
 stuff((select distinct ',' + nullif(category,'')
 from combined t2 where t2.product_name = t1.product_name
 for XML PATH(''),TYPE).value('.','VARCHAR(MAX)'),1,1,'') as category
 from combined t1