尝试将列连接到逗号分隔列表

时间:2014-05-05 08:45:27

标签: sql sql-server tsql

我有3个表,1个用于产品,1个用于分配产品的类别。 IM尝试做的是将名为stCategoryName的列连接到逗号分隔列表中的单个列。

基本上我有产品表包含每个产品的主键,我试图找出如何连接每个产品旁边的所有stcategoryName列,以便我可以简化回报

我想要得到的是以下内容。

stProductID     stCategoryName
123             category1,category2,category3


SELECT        
   dbo.StoreItemTracking.StCategoryID,
   dbo.StoreItemTracking.StProductID, 
   dbo.StoreItemTracking.viewOrder, 
   dbo.StoreCategories.StCategoryName, 
   dbo.Store_Products.PartNumber
FROM            
   dbo.StoreItemTracking 
   INNER JOIN dbo.StoreCategories 
      ON dbo.StoreItemTracking.StCategoryID = dbo.StoreCategories.StCategoryID 
   INNER JOIN dbo.Store_Products 
      ON dbo.StoreItemTracking.StProductID = dbo.Store_Products.ID

我坚持如何连接查询包含3个表的列。

任何帮助非常感谢

2 个答案:

答案 0 :(得分:1)

使用coalesce将类别转换为CSV:

参见示例:

DECLARE @EmployeeList varchar(100) 
SELECT @EmployeeList = COALESCE(@EmployeeList + ', ', '')  
    + CAST(Emp_UniqueID AS varchar(5))      
FROM SalesCallsEmployees  
WHERE SalCal_UniqueID = 1  
SELECT @EmployeeList

您也可以使用CTE或子查询。参见:

http://archive.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=createacommadelimitedlist

另一个不错的例子:

http://www.codeproject.com/Articles/21082/Concatenate-Field-Values-in-One-String-Using-CTE-i

此:

FId FName
--- ----
2    A
4    B
5    C
6    D
8    E

with:

;WITH ABC (FId, FName) AS
(
    SELECT 1, CAST('' AS VARCHAR(8000)) 
    UNION ALL
    SELECT B.FId + 1, B.FName +  A.FName + ', ' 
    FROM (And the above query will return
SELECT Row_Number() OVER (ORDER BY FId) AS RN, FName FROM tblTest) A 
    INNER JOIN ABC B ON A.RN = B.FId 
)
SELECT TOP 1 FName FROM ABC ORDER BY FId DESC

变为:

FName
----------------------------
A, B, C, D, E,

答案 1 :(得分:1)

不要了解您的产品和类别是如何连接的,但一般情况下,我这样做是为了创建以逗号分隔的列表。

SELECT table1.Id
      ,Csv
FROM table1
     CROSS APPLY (
         -- Double select so we can have an alias for the csv column
         SELECT (SELECT ',' + table2.Name
                 FROM table2
                 WHERE table2.Id = table1.Id
                 FOR XML PATH('')
                ) AS RawCsv
     ) AS CA1
     CROSS APPLY (
         -- Trim the first comma
         SELECT RIGHT(RawCsv, LEN(RawCsv) - 1) AS Csv
     ) AS CA2