SQL序数连接

时间:2015-10-28 02:45:24

标签: sql sql-server-2012 concatenation ordinal

我有一张桌子,看起来像这样。

Product ID | Description  | Order
100             | This is a       | 1
100             | for test         | 3
100             | Description | 2 
101             | Product 101| 1
406             | here              | 2
406             | Enter desc   | 1

我需要使用t-sql逻辑来连接并按照订单号对每个唯一的产品ID进行分组。

输出应如下所示:

Product ID| Description
100            | This is a Description for test
101            | Product 101
406            | Enter desc here

需要避免硬编码逻辑,因为系统中的用户可以扩展描述。

非常感谢所有回复

1 个答案:

答案 0 :(得分:0)

--Create Temporary Table
CREATE TABLE #Products
(
     [Product ID] INT
    ,[Description] VARCHAR(100)
    ,[Order] INT
);
GO

--Insert sample data into #Products
INSERT INTO #Products ([Product ID], [Description], [Order]) VALUES (100, 'This is a', 1);
INSERT INTO #Products ([Product ID], [Description], [Order]) VALUES (100, 'for test', 3);
INSERT INTO #Products ([Product ID], [Description], [Order]) VALUES (100, 'Description', 2);
INSERT INTO #Products ([Product ID], [Description], [Order]) VALUES (101, 'Product 101', 1);
INSERT INTO #Products ([Product ID], [Description], [Order]) VALUES (406, 'here', 2);
INSERT INTO #Products ([Product ID], [Description], [Order]) VALUES (406, 'Enter desc', 1);
GO

--GROUP BY [Product ID] to concatenate [Description] in the order of [Order]
SELECT
     [Product ID]
     ,ISNULL(MAX(CASE WHEN [Order] = 1 THEN       [Description] ELSE NULL END),'') +
      ISNULL(MAX(CASE WHEN [Order] = 2 THEN ' ' + [Description] ELSE NULL END),'') +
      ISNULL(MAX(CASE WHEN [Order] = 3 THEN ' ' + [Description] ELSE NULL END),'') AS [Description]
FROM #Products
GROUP BY [Product ID];

我确信有更好的方法可以做到这一点,但这很简单。对于有< = [Order]值的情况,我用ISNULL()包装了MAX()函数。