2017-04-14 90 views
0
select (select SUM(t.fees_amount)from unit u, payment p, type_of_fees t WHERE u.unit_id = p.unit_id AND p.stof = t.stof AND u.unit_id LIKE '%U1001%' 
     AND p.stat = 'not payed') "BLOCK 1(Not Payed)", 

     (select SUM(t.fees_amount)from unit u, payment p, type_of_fees t WHERE u.unit_id = p.unit_id AND p.stof = t.stof AND u.unit_id LIKE '%U1001%' 
     AND p.stat = 'payed') "BLOCK 1(Payed)", 

     (select SUM(t.fees_amount)from unit u, payment p, type_of_fees t WHERE u.unit_id = p.unit_id AND p.stof = t.stof AND u.unit_id LIKE '%U1002%' 
     AND p.stat = 'not payed') "BLOCK 2(Not Payed)", 

     (select SUM(t.fees_amount)from unit u, payment p, type_of_fees t WHERE u.unit_id = p.unit_id AND p.stof = t.stof AND u.unit_id LIKE '%U1002%' 
     AND p.stat = 'payed') "BLOCK 2(Payed)" 

from dual; 

有沒有其他方法可以解決這個問題?oracle sql plus腳本太長

回答

1

可以使用條件匯聚了這一點:

select sum(case when u.unit_id like '%U1001%' and p.stat = 'not payed' then t.fees_amount else 0 end) as "BLOCK 1(Not Payed)", 
    sum(case when u.unit_id like '%U1001%' and p.stat = 'payed' then t.fees_amount else 0 end) as "BLOCK 1(Payed)", 
    sum(case when u.unit_id like '%U1002%' and p.stat = 'not payed' then t.fees_amount else 0 end) as "BLOCK 2(Not Payed)", 
    sum(case when u.unit_id like '%U1002%' and p.stat = 'payed' then t.fees_amount else 0 end) as "BLOCK 2(Payed)" 
from unit u 
join payment p on u.unit_id = p.unit_id 
join type_of_fees t on p.stof = t.stof; 

而且你應該總是使用明確的聯接語法,而不是基於老逗號連接。

+0

這是因爲我的數據庫設計糟糕,並導致這個漫長的腳本? – user7868404

+0

@ user7868404 - 我認爲這是要求。由於您必須使用'like',因此查詢速度可能很慢。儘管我已經設法將你的四個選擇放入一個。 – GurV