简体   繁体   English

SQL 服务器使用 SUM 连接到新列

[英]SQL Server Concatenate To New Column With SUM

Please consider the following sample data:请考虑以下示例数据:

Part Loc Qty
A A-1 10
A A-5 15
A B-4 7
B B-5 10
B B-6 15

I can query easily enough to get the location qty for each part:我可以很容易地查询以获取每个部分的位置数量:

select
    pt.Part
    ,lc.Loc
    ,lc.LocQty Qty
from
    Part pt
left join
    Loc lc
on
    pt.Part = lc.Part

I can also sum the locations like so:我也可以像这样总结位置:

select
    pt.Part
    ,sum(lc.LocQty) TotalQty
from
    Part pt
left join
    Loc lc
on
    pt.Part = lc.Part
group by
    pt.Part

What I want to do now is instead concatenate into a new column, each location that the part appears, like so:我现在要做的是连接到一个新列,该部分出现的每个位置,如下所示:

Part TotalQty InLocations
A 32 A-1, A-5, B-4
B 25 B-5, B-6

What would be the best approach to this?最好的方法是什么?

Many thanks非常感谢

SQL SERVER replacement of GROUP_CONCAT() is STRING_AGG() .But STRING_AGG() was introduced in SQL Server 2017 version, you have to use combination of STUFF and For XML PATH to get your result. Z97778840A0100CB30C982828282828282828282828282828282828282828282828282828282828282828282828233333333338282828282828282828281333330333338238282828282828282820BY 330 330 330 330 330 330 330 330 330 330 toff in Z9778840A0CB30C982876741B0B0B0B0B5A2Z服务器替换For XML PATH GROUP_CONCAT()STRING_AGG() . STRING_AGG() STUFF

SELECT P.PART,SUM(QTY) AS TOTALQTY,
       INLOCATIONS = STUFF(
                     (
                      SELECT ', ' + PA.LOC 
                      FROM PART AS PA 
                      WHERE PA.PART = P.PART
                      FOR XML PATH('')
                     ), 1, 2, N''
                     ) 
 FROM PART P
 GROUP BY P.PART

Check Demo here 在这里查看演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM