2016-12-16 77 views
0

我需要你幫忙。Interbase SQL重做一個Select查詢

我有一個Interbase的SQL SELECT查詢:

選擇aps.fullname,aps.productvcode,aps.alccode,aps.capacity,CAST(圓(總和(情況下wp.capacity> 0,則WP .quantity * wp.capacity/10 else wp.quantity * wp.capacity end),4)as DECIMAL(18,4))as WBTotal from AP aps left加入Waybill_positions wp on wp.alccode = aps.alccode其中 wp.​​alccode = '0001821000001389010' 由aps.fullname, aps.productvcode,aps.alccode組,aps.capacity
UNION ALL
選擇aps.fullname ,aps.productvcode,aps.alccode,aps.capacity, Cast(Round(Sum(wp.capacity> 0 then wp.quantity * wp.capacity/10 else wp.quantity * wp.capacity end),4 )as DECIMAL(18,4))as WBTotal from AP aps left加入Waybill_out_positions wp on wp.alccode = aps.alccode 其中wp.alccode ='0001821000001389010'group by aps.fullname, aps.productvcode,aps.alccode ,aps.capacity

,這讓我這個:enter image description here

但我想從第二行的值「156,9750」是右邊一個單獨的列旁邊「WBTOTAL」,並有標題「WBOTOTAL」

怎麼辦呢?

回答

1

您可以使用CTE,像下面

with CTE1 as 
(
    Select aps.fullname, aps.productvcode, aps.alccode, aps.capacity, Cast(Round(Sum(case when wp.capacity>0 then wp.quantity * wp.capacity/10 else wp.quantity * wp.capacity end),4) as DECIMAL(18,4)) as WBTotal from AP aps left join Waybill_positions wp on wp.alccode=aps.alccode where wp.alccode='0001821000001389010' group by aps.fullname, aps.productvcode, aps.alccode, aps.capacity 
), 
CTE2 as 
(
    Select aps.fullname, aps.productvcode, aps.alccode, aps.capacity, Cast(Round(Sum(case when wp.capacity>0 then wp.quantity * wp.capacity/10 else wp.quantity * wp.capacity end),4) as DECIMAL(18,4)) as WBTotal from AP aps left join Waybill_out_positions wp on wp.alccode=aps.alccode where wp.alccode='0001821000001389010' group by aps.fullname, aps.productvcode, aps.alccode, aps.capacity 
) 
Select CTE1.fullname, CTE1.productvcode, CTE1.alccode, CTE1.capacity, CTE1.WBTotal, CTE2.WBTotal as WBOTOTAL 
From CTE1 
join CTE2 
on CTE1.productvcode = CTE2.productvcode 
and CTE1.alccode = CTE2.alccode 
+0

曾爲...謝謝..我可以添加其它表一樣的方式嗎? – SovereignSun

+1

@SovereignSun,確定您可以在一個查詢中擁有多個CTE。您可以在此鏈接中有更多參考https://msdn.microsoft.com/en-us/library/ms175972.aspx –

+0

非常感謝! – SovereignSun