【问题标题】:Move an object up and separate based on item向上移动对象并根据项目分开
【发布时间】:2020-04-05 02:18:13
【问题描述】:

我有以下问题:

Apple  | Document 1 | 5
Orange | Document 2 | 4
Apple  | Document 3 | 7

我希望查询发生的情况如下:

Apple  | Document 1 | Document 3 | 12
Orange | Document 2              | 7

有没有为你做这件事的函数?

【问题讨论】:

    标签: sql-server tsql aggregate-functions


    【解决方案1】:

    如果您正在使用 Pre SQL Server 2017,您可以尝试使用 Stuff and XML Path 的组合

    SELECT fruit, 
        abc = STUFF(
                     (SELECT '|' + doc FROM test t1
                         WHERE t1.fruit = t2.fruit FOR XML PATH ('')), 1, 1, ''
                   ), SUM(value)
    FROM test t2 GROUP BY fruit
    

    http://sqlfiddle.com/#!18/ce52e/2

    STUFF and XML PATH 在这里解释得很好

    How Stuff and 'For Xml Path' work in Sql Server

    【讨论】:

    • 太好了,我会在几天后试一试。谢谢。是否有特定的术语,或者这个运动的名称可以更好地帮助我的 google-fu?
    【解决方案2】:

    在 SQL Server 2017 中,您可以将 STRING_AGG 函数与 GROUP BY 一起使用:

    SELECT fruit, STRING_AGG(document, '|') AS documents, SUM(value) AS total
    FROM t
    GROUP BY fruit
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-03-18
      • 2015-11-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-29
      • 1970-01-01
      相关资源
      最近更新 更多