如何将这两个查询合并为1?

时间:2014-03-03 10:51:35

标签: sql sql-server

我想添加一个commaseperated列,其中包含该产品的产品类别名称列表。这是我的数据模型: enter image description here

我在此查询中得到了所有产品详细信息:

select d.name as 'Dealer Name',c.commissionamount as 'Commission Amount',c.createddate as 'Commission Created Date' ,p.name as 'Product Name'
from commission c
join dealer d 
on d.dealerid=c.dealerid
join product p on c.productid=p.productid
join productcategorymapping pcm on p.ProductId=pcm.ProductId
join ProductCategory pc on pc.ProductCategoryId=pcm.ProductCategoryId

我只是想为这个查询添加每个产品的csv列,我只是不知道如何加入2:

select stuff((
SELECT ',' + pc.Name
FROM ProductCategory pc
join ProductCategoryMapping pcm on pcm.ProductCategoryId=pc.ProductCategoryId
join Product p1 on p1.ProductId=pcm.ProductId
and p1.ProductId=1
FOR XML PATH('')),1,1,'');

它表示productId = 1,但这是需要加入其他查询的地方。 所以结果会是这样的:

DealerName  | Amount |date|product Name|csv
TestDealer1 | 105.25 |..  |ProdA       |CatA,CatC,CatF

我还为此创建了一个sqlfiddle:http://sqlfiddle.com/#!6/d574e/4

2 个答案:

答案 0 :(得分:1)

试试这个..

select
       d.name             AS [Dealer Name]
      ,c.commissionamount AS [Commission Amount]
      ,c.createddate      AS [Commission Created Date] 
      ,p.name             AS [Product Name]
      ,stuff((SELECT ', ' + pcci.Name
              FROM ProductCategory pcci
              join ProductCategoryMapping pcmi 
              on pcmi.ProductCategoryId=pcci.ProductCategoryId
              join Product p1i 
              on p1i.ProductId=pcmi.ProductId
              WHERE p1i.ProductId = p.productid
              FOR XML PATH(''),TYPE).value('.','NVARCHAR(MAX)'),1,2,'')
                           AS [CSV]

from commission c join dealer d 
on d.dealerid=c.dealerid
join product p 
on c.productid=p.productid;

Working SQL FIDDLE

答案 1 :(得分:0)

只需将Select语句中的两个组合起来就可以完成:

select DISTINCT d.name as 'Dealer Name',
c.commissionamount as 'Commission Amount',
c.createddate as 'Commission Created Date' ,
p.name as 'Product Name',
stuff((
SELECT ',' + pc.Name
FROM ProductCategory pc
join ProductCategoryMapping pcm on pcm.ProductCategoryId=pc.ProductCategoryId
join Product p1 on p1.ProductId=pcm.ProductId
and p1.ProductId=1
FOR XML PATH('')),1,1,'') as reqCol
from commission c
join dealer d 
on d.dealerid=c.dealerid
join product p 
on c.productid=p.productid
join productcategorymapping pcm 
on p.ProductId=pcm.ProductId
join ProductCategory pc 
on pc.ProductCategoryId=pcm.ProductCategoryId;

查看http://sqlfiddle.com/#!6/d574e/12