需要按日期分隔的逗号分隔产品值

我有下面的表结构

create TABLE PRODUCTDeatils 
(
    Product varchar(50),
    Date Datetime
)

enter image description here

我想要一个输出,在其中我得到逗号分隔的列表,这些列表具有不同的值,但按日期排序。

我首先通过以下查询拆分值

SELECT DISTINCT
    LTRIM(RTRIM(value)) AS Product, date
INTO #tmp3
FROM PRODUCTDeatils
CROSS APPLY STRING_SPLIT(LTRIM(RTRIM(Product)), ',')    

SELECT * 
FROM #tmp3 
ORDER BY date

enter image description here

然后我使用下面的两个查询来实现它,但是没有成功。

查询1:

DECLARE @cols AS NVARCHAR(MAX);

SELECT @COLS =  substring(list, 1, LEN(list) - 1)
FROM   
    (SELECT 
         list = (SELECT DISTINCT Product + ';'
                 FROM #tmp3
                 ORDER BY Product + ';'
                 FOR XML PATH(''), TYPE).value('.', 'nvarchar(MAX)')) AS T

SELECT @COLS

查询2:

 SELECT  
     STUFF((SELECT '; ' + Product
            FROM 
                (SELECT DISTINCT TOP 100
                     Product,date
                 FROM #tmp3) x  
            ORDER BY date
            FOR XML PATH('')), 1, 2, '') Text

enter image description here

我想要上面的输出,但是bat应该只出现一次。

评论