2013-09-24 64 views
0

我现在有在SQL Server以下查询2012的单一一行被返回以用于字段除了“cd.billed_amt为[DISB开帐单]”,其可以具有用于单个bill_num多个结果。SQL - 总结在结果单塔集

我希望做的是总结只有[DISB发单]列,因此初始8行的结果集将成为两行的结果集。

select distinct bbl.bill_num, 
     bb.tran_type, 
     hm.clnt_matt_code, 
     bb.tran_date, 
     bb.period, 
     cd.billed_amt as [Disb Billed], 
     fees_amt 
    from blt_bill_amt bb 
    join hbm_matter hm on bb.matter_uno = hm.matter_uno 
    join blt_billm bbm on bbm.billm_uno = bb.billm_uno 
    join blt_bill bbl on bbl.tran_uno = bbm.bill_tran_uno 
    left outer join cdt_disb cd on cd.bill_tran_uno = bbl.tran_uno 
where bb.tran_type in ('WO', 'WOX') 
    and bb.period = '201401' 
    and bbl.bill_num = 231728 
order by bb.tran_type, bbl.bill_num 

当前结果集

bill_num tran_type clnt_matt_code  tran_date    period Disb Billed fees_amt 
------------------------------------------------------------------------------------------------ 
231728 WO   N10118.1016   2013-04-18 00:00:00.000 201401 3.00   8.06 
231728 WO   N10118.1016   2013-04-18 00:00:00.000 201401 20.00   8.06 
231728 WO   N10118.1016   2013-04-18 00:00:00.000 201401 38.00   8.06 
231728 WO   N10118.1016   2013-04-18 00:00:00.000 201401 42.50   8.06 
231728 WO   N10118.1016-0001 2013-04-18 00:00:00.000 201401 3.00   0.94 
231728 WO   N10118.1016-0001 2013-04-18 00:00:00.000 201401 20.00   0.94 
231728 WO   N10118.1016-0001 2013-04-18 00:00:00.000 201401 38.00   0.94 
231728 WO   N10118.1016-0001 2013-04-18 00:00:00.000 201401 42.50   0.94 

所需的结果集

bill_num tran_type clnt_matt_code  tran_date    period Disb Billed fees_amt 
------------------------------------------------------------------------------------------------ 
231728 WO   N10118.1016   2013-04-18 00:00:00.000 201401 103.50  8.06 
231728 WO   N10118.1016-0001 2013-04-18 00:00:00.000 201401 103.50  0.94 

回答

0

你需要组使用GROUP您的搜寻结果reference

因此,对于你的例子:

select distinct bbl.bill_num, 
     bb.tran_type, 
     hm.clnt_matt_code, 
     bb.tran_date, 
     bb.period, 
     SUM(cd.billed_amt) as [Disb Billed], --sum the billed column 
     fees_amt 
    from blt_bill_amt bb 
    join hbm_matter hm on bb.matter_uno = hm.matter_uno 
    join blt_billm bbm on bbm.billm_uno = bb.billm_uno 
    join blt_bill bbl on bbl.tran_uno = bbm.bill_tran_uno 
    left outer join cdt_disb cd on cd.bill_tran_uno = bbl.tran_uno 
where bb.tran_type in ('WO', 'WOX') 
    and bb.period = '201401' 
    and bbl.bill_num = 231728 
GROUP BY bbl.bill_num, --add group by 
     bb.tran_type, 
     hm.clnt_matt_code, 
     bb.tran_date, 
     bb.period, 
     fees_amt 
order by bb.tran_type, bbl.bill_num 
+0

感谢克里斯,正是我一直在努力做的事。 –

+0

没问题 - 很高兴帮助。你能将这标记为可接受的解决方案吗? –