我目前在SQL Server 2012中有以下查询。除了'cd.billed_amt as [Disb Billed]'之外的字段将返回一行,这可以为单个bill_num提供多个结果。
我想要做的只是汇总[Disb Billed]列,以便初始的8行结果集将成为2行结果集。
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 :(得分:0)
您需要使用GROUP BY 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