2013-09-24 71 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

沒問題 - 很高興幫助。你能將這標記爲可接受的解決方案嗎? –