2012-09-28 129 views
2

我有一個工作查詢,不確定它是否有效。SQL查詢效率

表列:

  1. P_TYPE:可以是字符串賣出,cancelsell,銀行,cancelbank要執行
  2. ID
  3. FID
  4. 單元

操作:

  1. SUM(單位)爲每個過程類型銷售,取消銷售,銀行,取消銀行。
  2. SUM(單位賣出) - SUM(單位cancelsell),SUM(單位銀行) - SUM(單位cancelbank)

注意:我還檢查ID和每個FID選擇,雖然我需要檢查所有選擇相同的值。

現有的查詢:

select sell-cancelsell scount, bank-cancelbank bcount from 

    (select sum(a.unit) as sell from table1 a where 
    a.p_type = 'Sell' and a.id=1 and a.fid=2), 

    (select sum(c.unit) as cancelsell from table1 c where  
    c.p_type = 'CancelSell' and c.id=1 and c.fid=2), 

    (select sum(b.unit) as bank from table1 b where  
    b.p_type = 'Bank' and b.id=1 and b.fid=2), 

    (select sum(d.unit) as cancelbank from table1 d where 
    d.p_type = 'CancelBank' and d.id=1 and d.fid=2) 

是不夠好?如果任何人都可以建議一種更高效的方法,那就太好了。

回答

5

你可以做到這一點

select 
sum(Case when a.p_type = 'sell' then a.unit else null end) as sellUnit, 
sum(Case when a.p_type = 'CancelSell' then a.unit else null end) as CancelSellUnit, 
sum(Case when a.p_type = 'Bank' then a.unit else null end) as BankUnit , 
sum(Case when a.p_type = 'CancelBank' then a.unit else null end) as CancelBankUnit 
from table1 a where and a.id=1 and a.fid=2 
+0

+1你打我:) –

+0

@rs。非常感謝你。我知道我必須使用Case,但沒有得到正確的結果。再次感謝您 –

2

試試這個:

SELECT 
     SUM(CASE WHEN P_TYPE = 'SELL' THEN UNIT END) - 
     SUM(CASE WHEN P_TYPE = 'CANCELSELL' THEN UNIT END) AS SCOUNT, 
     SUM(CASE WHEN P_TYPE = 'BANK' THEN UNIT END) - 
     SUM(CASE WHEN P_TYPE = 'CANCELBANK' THEN UNIT END) AS BCOUNT 
FROM TABLE1 
WHERE ID=1 AND FID=2 
+0

謝謝。我實際上使用CASE這種方式! –

0
select temp1.sumunit - temp2.sumunit,temp3.sumunit-temp4.sumunit from 
(select p_type,sum(unit) as sumunit from table1 
group by p_type) as temp1 
inner join 
(select p_type,sum(unit) as sumunit from table1 
group by p_type) as temp2 on temp2.p_type = 'cancelsell' 
inner join 
(select p_type,sum(unit) as sumunit from table1 
group by p_type) as temp3 on temp3.p_type = 'bank' 
inner join 
(select p_type,sum(unit) as sumunit from table1 
group by p_type) as temp4 on temp4.p_type='cancelbank' 
where temp1.p_type='sell' 
and temp1.id = 1 and temp1.fid = 2 
and temp2.id = 1 and temp2.fid = 2 
and temp3.id = 1 and temp3.fid = 2 
and temp4.id = 1 and temp4.fid = 2