如何在存储过程中使用名称进行求和和分组?

时间:2012-08-16 04:25:28

标签: sql sql-server sql-server-2008 stored-procedures

我想总结钱栏,但我希望群组名称和代码处于状态。

这是存储过程代码[Sql Server 2008]:

SELECT um.upmoney as 'money'
,um.pId as 'code',um.FName as 'name',up.status as 'statusmoney'
From tb_upmoney um inner join tb_pID up on up.uId=um.pId

结果:

money | code | name | statusmoney
200.00 | 00001 | fin | 1
100.00 | 00001 | fin | 1
50.00 | 00001 | fin | 1
100.00 | 00002 | welson | 1
200.00 | 00002 | welson | 2
100.00 | 00002 | welson | 2
50.00 | 00002 | welson | 2
0.00 | 00002 | welson | 2

但我想:

money | code | name | statusmoney
250.00 | 00001 | fin | 1
100.00 | 00002 | welson | 1
250.00 | 00002 | welson | 2

4 个答案:

答案 0 :(得分:1)

您需要SUM(UM.upmoney)并将剩余字段分组如下:

SELECT SUM(um.upmoney) AS 'money',
       um.pId AS 'code',
       um.FName AS 'name',
       up.status AS 'statusmoney'
FROM tb_upmoney um 
    INNER JOIN tb_pID up 
    ON up.uId=um.pId
GROUP BY um.pId, um.FName, up.status

请参阅GROUP BY clause with an aggregator 'SUM()'

的示例

答案 1 :(得分:0)

怎么样

SELECT  SUM(um.upmoney) as 'money',
        um.pId as 'code',
        um.FName as 'name',
        up.status as 'statusmoney' 
From    tb_upmoney um inner join 
        tb_pID up   on  up.uId=um.pId 
GROUP BY    um.pId,
            um.FName,
            up.status

SUM (Transact-SQL)

GROUP BY (Transact-SQL)

答案 2 :(得分:0)

SELECT sum(um.upmoney) as 'money',um.pId as 'code',um.FName as 'name',up.status as 'statusmoney'
From tb_upmoney um inner join tb_pID up on    up.uId=um.pId group by um.pId, um.FName, up.status

答案 3 :(得分:0)

检查这个

SELECT Sum(um.upmoney)为'money',um.pId为'code',um.FName为'name',up.status为'statusmoney' 从tb_upmoney um inner join tb_pID up up.uId = um.pId GROUP BY um.FName,um.pId