0

假设我们有一个表,例如:

Number Value GroupValue
1      FOO    GR1
22     BAR    GR2
100    FOO3   GR1
20     BAR23  GR2

我想根据组值获取这些行的总和值,而且,我想查看它在另一列中分组的行,例如:

SUM  values groups
101  FOO,FOO3 GR1
42   BAR,BAR23 GR2

我怎样才能在sql中实现这一点?

试过:

> SELECT  SUM(ID) AS SUM ,
        STUFF(( SELECT  ',' + A
                FROM    dbo.Table_1 AS T2
                WHERE   A = T2.A
              FOR
                XML PATH('')
              ), 1, 1, '') AS A ,
        B
FROM    dbo.Table_1 AS T
GROUP BY B ,
        A

但这不能正确处理组...

4

4 回答 4

1

您不能使用SELECTGROUP BY. 您可以通过将列表与聚合(cte/子查询)分开来解决此问题:

WITH cte AS (SELECT  *
                     ,STUFF(( SELECT  ',' + Value
                              FROM    Table1 AS T2
                              WHERE   T.GroupValue = T2.GroupValue
                              FOR XML PATH('')
                            ), 1, 1, '') AS Value_List
              FROM    Table1 AS T)
SELECT  SUM(Number) AS Total
       ,Value_List
       ,GroupValue
FROM cte
GROUP BY Value_List, GroupValue

演示:SQL 小提琴

或者您可以使用分区SUM()(窗口函数):

SELECT  DISTINCT SUM(Number) OVER(PARTITION BY GroupValue) AS Total
        ,STUFF(( SELECT  ',' + Value
                 FROM    Table1 AS T2
                 WHERE   T.GroupValue = T2.GroupValue
                 FOR XML PATH('')
               ), 1, 1, '') AS Value_List
        ,GroupValue
FROM    Table1 AS T

演示:SQL 小提琴

于 2013-09-18T20:01:12.053 回答
0

你只需要做一个小的改变,将没有组的 SQL 粘贴到另一个有组的选择中。我想我正确地转换了你的 SQL:

SELECT SUM(ID) as IdSum, B FROM (
SELECT  ID,
        STUFF(( SELECT  ',' + A
                FROM    dbo.Table_1 AS T2
                WHERE   A = T2.A
              FOR
                XML PATH('')
              ), 1, 1, '') AS B
FROM    dbo.Table_1 AS T) AS B2
GROUP BY B
于 2013-09-18T19:53:01.153 回答
0

您可以将列表嵌套更深一层

...

SELECT
    IDList1=    
        SUBSTRING((
            SELECT  ', ' + CAST(TargetID AS NVARCHAR(10))
            FROM 
            (
                SELECT 
                   DISTINCT TargetID 
                FROM 
                   TargetTable 
                WHERE 
                  TargetIDTableField2=MAINQUERYALIAS.TargetIDTableField2
            )
            AS UP2
            ORDER BY 
             TargetID FOR XML PATH( '' )
        ), 3, 1000 )
FROM
(
   ...
) AS MAINQUERYALIAS
于 2013-09-18T19:54:04.517 回答
0

下载这个并运行这个脚本http://groupconcat.codeplex.com/releases/view/106409 你可以像这样简单地解决你的问题

select SUM(Number), dbo.GROUP_CONCAT(Value)
from Table_2 
group by GroupValue

如果这个答案是您的问题,请标记为已回答谢谢

于 2013-09-19T02:28:19.597 回答