sql server:基于id连接行

时间:2015-07-20 21:01:29

标签: sql sql-server pivot-table

我试图基本上获取特定商家的所有标签,我希望根据商家ID对标签进行分组(请参阅下面的内容,了解我当前查询的内容以及我希望的内容得到)。一个商家可能有多个标签,但Tag的每一行只有一个商家。此外,商家和标签通过表商家标签关联,该商标标签只保存标签的ID和商家的ID。

查询

select m.MerchantId, m.MerchantName, t.TagName
from Merchant m 
inner join MerchantTags mt on m.MerchantId=mt.MerchantId 
inner join tag t on mt.TagId=t.TagId 
where m.MerchantId=162

结果

MerchantId | MerchantName | TagName  
162        |   merchant   |  tag1
162        |   merchant   |  tag2 

期望的结果

MerchantId | MerchantName | TagName | TagName  
162        |   merchant   |  tag1   | tag2

MerchantId | MerchantName | TagName   
162        |   merchant   |  tag1, tag2

2 个答案:

答案 0 :(得分:0)

测试数据

DECLARE @Table TABLE (MerchantId INT, MerchantName VARCHAR(20), TagName VARCHAR(20))
INSERT INTO @Table VALUES   
(162 ,'merchant','tag1'),
(162 ,'merchant','tag2')

查询

SELECT t.MerchantId
      ,t.MerchantName
      ,STUFF((SELECT ',' + TagName
              FROM @Table 
              WHERE t.MerchantId   = MerchantId
                AND t.MerchantName = MerchantName
              FOR XML PATH(''),TYPE)
              .value('.','NVARCHAR(MAX)'),1,1,'') AS TagName
FROM @Table t 
GROUP BY t.MerchantId
      ,t.MerchantName

结果

╔════════════╦══════════════╦═══════════╗
║ MerchantId ║ MerchantName ║  TagName  ║
╠════════════╬══════════════╬═══════════╣
║    162     ║   merchant   ║ tag1,tag2 ║
╚════════════╩══════════════╩═══════════╝

答案 1 :(得分:0)

另一种方式首先 我认为如果你把你的表格结构变得更好。 假设你的表是这样的

DECLARE @Merchants  TABLE (MerchantId INT, MerchantName VARCHAR(20))
INSERT INTO @Merchants  VALUES  
 (162 ,'merchant1')
,(163 ,'merchant2');

DECLARE @Tags TABLE (TagId INT, TagName VARCHAR(20))
INSERT INTO @Tags  VALUES   
 (1 ,'Tag01')
,(2 ,'Tag02')
,(3 ,'Tag03');

DECLARE @MerchantsTags TABLE (MerchantId INT, TagId INT)
INSERT INTO @MerchantsTags  VALUES   
 (162 ,1)
,(162 ,2)
,(163 ,1)
,(163 ,2)
,(163 ,3);

然后你可以

SELECT MT.MerchantId,T.TagId,T.TagName
INTO #TMT
FROM @MerchantsTags MT
LEFT JOIN @Tags T ON MT.TagId = T.TagId


SELECT DISTINCT M.MerchantId,M.MerchantName,T1.TagName AS 'Tag1',T2.TagName AS 'Tag2',T3.TagName AS 'Tag3'
FROM @Merchants M
LEFT JOIN #TMT T1 ON M.MerchantId = T1.MerchantId AND T1.TagId = 1
LEFT JOIN #TMT T2 ON M.MerchantId = T2.MerchantId AND T2.TagId = 2
LEFT JOIN #TMT T3 ON M.MerchantId = T3.MerchantId AND T3.TagId = 3
--LEFT JOIN #TMT T4 ON M.MerchantId = T4.MerchantId AND T4.TagId = 4

DROP TABLE #TMT

如果您希望将标签放在一个列中,您可以用这样的

替换您的SELECT
SELECT DISTINCT M.MerchantId,M.MerchantName,COALESCE(T1.TagName,'') +','+COALESCE(T2.TagName,'')+','+COALESCE(T3.TagName,'') AS 'Tag'

Here是SQLFiddle版本