分组依据 - 如何连接Grouped列

时间:2018-01-11 15:30:53

标签: sql sql-server

我坚持这一点,请提供一些指导。

我有3列,我使用SalesDateTime

DATEPART分组

到目前为止,一切都运行良好,但我想添加第3列,其中包含连接的产品说明e.i Good product 1,Good product 2,Good product 3

这是我的剧本

CREATE TABLE #Sales
(
    Name VARCHAR (100),
    SalesDateTime DATETIME,
    Description VARCHAR (100)     
)


GO
INSERT INTO #Sales
SELECT 'Product1',
       '2012-04-01 00:00:00.000',
       'Good product 1'
UNION ALL
SELECT 'Product2',
       '2012-04-02 00:00:00.000',
       'Good product 2'
UNION ALL
SELECT 'Product3',
       '2012-04-02 00:00:00.000',
       'Good product 3'
UNION ALL
SELECT 'Product4',
       '2012-04-03 00:00:00.000',
       'Good product 4'
UNION ALL
SELECT 'Product5',
       '2012-04-03 00:00:00.000',
       'Good product 5'
UNION ALL
SELECT 'Product1',
       '2012-04-30 00:00:00.000',
       'Good product 6'
UNION ALL
SELECT 'Product1',
       '2012-04-30 00:00:00.000',
       'Good product 7'
UNION ALL
SELECT 'Product1',
       '2012-05-02 00:00:00.000',
       'Good product 8'
UNION ALL
SELECT 'Product5',
       '2012-05-02 00:00:00.000',
       'Good product 9'
UNION ALL
SELECT 'Product5',
       '2012-05-02 00:00:00.000',
       'Good product 10'


GO

--GROUP BY DAY of Year
SELECT   count(*) AS SalesCount, DATEPART(dayofyear,SalesDateTime) Day
FROM #Sales
GROUP BY DATEPART(dayofyear,SalesDateTime)

GO 
DROP TABLE #Sales

2 个答案:

答案 0 :(得分:0)

所以你可以在那个列上使用GROUP_CONCAT

为这个案例量身打造

SELECT count(*) AS SalesCount, 
       DATEPART(dayofyear,SalesDateTime) AS Day, 
       GROUP_CONCAT(Description SEPARATOR ',') AS details
FROM #Sales
GROUP BY DATEPART(dayofyear,SalesDateTime)

......我最近了解了功能: - )

答案 1 :(得分:0)

感谢您的每一个答案,这些答案引导我走上了正确的道路!

解决方案

SELECT   count(*) AS SalesCount, DATEPART(dayofyear,SalesDateTime) Day, ISNULL(MAX(Description),'') +','+ ISNULL(MAX(Description),'') +','+ ISNULL(MAX(Description),'') AS FinalColumn
FROM #Sales
GROUP BY DATEPART(dayofyear,SalesDateTime)

GO 
DROP TABLE #Sales

我使用ISNULL(MAX(Description),'')

连接