使用T-SQL添加两个nvarchar列

时间:2018-04-01 09:50:28

标签: sql sql-server tsql

表格结构

CREATE TABLE [dbo].[StackQuestion]
(
    [ID] [BIGINT] IDENTITY(1,1) NOT NULL,
    [Product_Id] [BIGINT] NULL,
    [Quantity] [DECIMAL](18, 6) NULL,
    [Description] [NVARCHAR](MAX) NULL,

    CONSTRAINT [PK_StackQuestion] 
        PRIMARY KEY CLUSTERED ([ID] ASC)
)

演示数据

INSERT [dbo].[StackQuestion] ([ID], [Product_Id], [Quantity], [Description]) 
VALUES (1, 10, CAST(50.000000 AS Decimal(18, 6)), N'Description1'), 
       (2, 20, CAST(10.000000 AS Decimal(18, 6)), N'StackDesc'),
        3, 10, CAST(10.000000 AS Decimal(18, 6)), N'Descrip2')
GO

所以基本上我需要按产品ID对这些列进行分组并总计它们的总数量。我可以通过简单的查询来实现,例如

SELECT 
    MAX(ID) AS LastID, Product_Id, SUM(Quantity) AS Quantity 
FROM 
    stackquestion
GROUP BY 
    Product_Id

重点是如何获得该组中所有项目的完整描述。我的描述列需要包含该组中的所有描述(nvarchar的SUM)

输出应该是这样的:

Desc

3 个答案:

答案 0 :(得分:2)

如果是SQL Server 2017或SQL Server Vnext,SQL Azure可以使用string_agg,如下所示

SELECT 
    MAX(ID) AS LastID, Product_Id, SUM(Quantity) AS 
    Quantity,string_agg(concat( [Description]), CHAR(13)) AS Description

FROM 
    stackquestion
GROUP BY 
    Product_Id

答案 1 :(得分:0)

根据@Andomar的说法,其中一个解决方案是查询STUFF

SELECT 
    MAX(ID) AS LastID, Product_Id, SUM(Quantity) AS Quantity,
    Description = STUFF((SELECT ',' + [Description] 
                         FROM stackquestion c 
                         WHERE c.Product_Id = stackquestion.Product_Id 
                         FOR XML PATH('')), 1, 1, '')
FROM 
    stackquestion
GROUP BY
    Product_Id

答案 2 :(得分:0)

超出您的要求,但拥有您想要的数据

SELECT ID, Product_Id, Quantity
     , SUM(Quantity) over (partition by Product_Id) AS SumQuantity 
FROM stackquestion
ORDER BY 
    Product_Id, ID