SQL查询效率

时间:2012-09-28 13:18:32

标签: sql oracle

我有一个有效的查询,不确定它是否有效。

表格列:

  1. p_type:可以是STRING sell,cancelsell,bank,cancelbank
  2. ID
  3. 单元
  4. 要执行的操作:

    1. 每个流程类型的SUM(单位)sell,cancelsell,bank,cancelbank。
    2. SUM(出售单位) - SUM(取消单位),SUM(单位为银行) - SUM(取消银行单位)
    3. 注意:我也在检查每个选择中的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)
      

      够好吗?如果有人可以建议一种方法,使其更有效,那将是伟大的。

3 个答案:

答案 0 :(得分: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 

答案 1 :(得分: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 

答案 2 :(得分: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