求助求助!!!如何将查询出来的多条记录按照指定的两个字段汇总成一行记录

qq_207100010 2015-11-15 07:48:46
如何将查询出来的多条记录按照指定的两个字段汇总成一行记录
这是我现有语句
select FYear ,FAccountID,'B','' ,'111','111',
case when FPeriod='1' and FBeginBalance>0 then ABS(convert(money,FBeginBalance)) ELSE 0 end ,
case when FPeriod='1' and FBeginBalance<0 then ABS(convert(money,FBeginBalance)) ELSE 0 end ,
case when FPeriod='1' then convert(money,FCredit) ELSE 0 end,
case when FPeriod='1' then convert(money,FDebit) ELSE 0 end,
case when FPeriod='2' then convert(money,FCredit) ELSE 0 end,
case when FPeriod='2' then convert(money,FDebit) ELSE 0 end,
case when FPeriod='3' then convert(money,FCredit) ELSE 0 end,
case when FPeriod='3' then convert(money,FDebit) ELSE 0 end,
case when FPeriod='4' then convert(money,FCredit) ELSE 0 end,
case when FPeriod='4' then convert(money,FDebit) ELSE 0 end,
case when FPeriod='5' then convert(money,FCredit) ELSE 0 end,
case when FPeriod='5' then convert(money,FDebit) ELSE 0 end,
case when FPeriod='6' then convert(money,FCredit) ELSE 0 end,
case when FPeriod='6' then convert(money,FDebit) ELSE 0 end,
case when FPeriod='7' then convert(money,FCredit) ELSE 0 end,
case when FPeriod='7' then convert(money,FDebit) ELSE 0 end,
case when FPeriod='8' then convert(money,FCredit) ELSE 0 end,
case when FPeriod='8' then convert(money,FDebit) ELSE 0 end,
case when FPeriod='9' then convert(money,FCredit) ELSE 0 end,
case when FPeriod='9' then convert(money,FDebit) ELSE 0 end,
case when FPeriod='10' then convert(money,FCredit) ELSE 0 end,
case when FPeriod='10' then convert(money,FDebit) ELSE 0 end,
case when FPeriod='11' then convert(money,FCredit) ELSE 0 end,
case when FPeriod='11' then convert(money,FDebit) ELSE 0 end,
case when FPeriod='12' then convert(money,FCredit) ELSE 0 end,
case when FPeriod='12' then convert(money,FDebit) ELSE 0 end,
case when FPeriod='13' then convert(money,FCredit) ELSE 0 end,
case when FPeriod='13' then convert(money,FDebit) ELSE 0 end,'0'
from t_Balance where FCurrencyID=1 and FYear='2008'and faccountid='1003'
查询出来结果为图片1

需要将查询出来的表按照前两个字段相同的话就汇总成一条记录,后面为金额字段则汇总求和
...全文
47 点赞 收藏 2
写回复
2 条回复
切换为时间正序
当前发帖距今超过3年,不再开放新的回复
发表回复
Tiger_Zhao 2015-11-16
    SELECT FYear ,FAccountID,
           SUM(M1) AS M1,
           SUM(M2) AS M2,
           ...
      FROM ( -- 原先的查询,给每个字段都指定列名
            select FYear ,FAccountID,
            case when FPeriod='1' and  FBeginBalance>0 then ABS(convert(money,FBeginBalance)) ELSE 0 end AS M1,
            case when FPeriod='1' and  FBeginBalance<0 then ABS(convert(money,FBeginBalance)) ELSE 0 end AS M2,
            ...
           ) t
  GROUP BY FYear ,FAccountID
回复
qq_207100010 2015-11-15
各位大神指导指导
回复
相关推荐
发帖
疑难问题
创建于2007-09-28

2.1w+

社区成员

MS-SQL Server 疑难问题
申请成为版主
帖子事件
创建了帖子
2015-11-15 07:48
社区公告
暂无公告