Sql Server - 获取总计行的ID

时间:2013-02-01 08:20:04

标签: sql-server-2008

我有下表t_vouchers:

id  code  amount  isactive
1   a1    10      1
2   a2    20      0
3   a3    30      1

我想计算所有有效凭证的总和(金额),但也要获得另一列,其中包含此总和中包含的ID列表。如下所示:

sum   ids
40    1,3

查询类似于:

 select sum(amount) /* ? how to get here the ids stuffed in a comma separated string ? */
 from t_vouchers
 where isactive = 1

1 个答案:

答案 0 :(得分:1)

这应该有效:

 select sum(amount) sum,
        (
        STUFF((
            SELECT  DISTINCT ',' + CAST(a.id AS VARCHAR(100))
            FROM    t_vouchers a
            WHERE   a.isactive = 1
            FOR XML PATH('')
            ),1,1,'')
        ) ids
 from t_vouchers
 where isactive = 1

这是SQL Fiddle