2

我有下表 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
4

1 回答 1

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 小提琴

于 2013-02-01T08:26:50.463 回答