簡體   English   中英

改進包含多個子查詢的SQL查詢

[英]Improve SQL Query that contains multiple sub queries

我有幾次遇到過SQL查詢的情況,輸出是正確的,但是我想知道是否有更好的方法來做,因為感覺就像我重復相同的公式很多次並運行太多的子查詢

 select s.StockId,

-- THESE ARE ALL REPEATED - CAN I GET ALL VALUES IN 1 QUERY?
isnull((select top 1 Cost from StockCosts sc where sc.Disabled = 0 and sc.StockId = s.StockId and ChargeType = 1),0) as VendorRecovery,
isnull((select top 1 Cost from StockCosts sc where sc.Disabled = 0 and sc.StockId = s.StockId and ChargeType = 2),0) as VendorCommission,

--THESE BOTTOM 3 ARE TO GET THE TOTALS, AGAIN REPEATED STATEMENTS?
(select SUM(Cost) from StockCosts sc where sc.Disabled = 0 and sc.StockId = s.StockId ) as VendorChargesNet,
(select (SUM(Cost) / 100) * st.VATRate from StockCosts sc where sc.Disabled = 0 and sc.StockId = s.StockId ) as VendorChargesVAT,
(select SUM(Cost) + (SUM(Cost) / 100) * st.VATRate from StockCosts sc where sc.Disabled = 0 and sc.StockId = s.StockId ) as VendorChargesTotal

from SaleTrans st 
inner join Stock s on st.StockId = s.StockId 

相關標量子查詢通常可以重寫為外部聯接。

而且,當您以相同的條件多次訪問同一張表時,您可能會將它們組合成一個派生表 (或Common Table Expression )。

這可能返回相同的結果:

select sc.*
from SaleTrans st 
inner join Stock s
left join 
 ( select
      min(case when ChargeType = 1 then cost end) as VendorRecovery -- or MAX?
     ,min(case when ChargeType = 2 then cost end) as VendorCommission
     ,SUM(Cost) as VendorChargesNet
     ,(SUM(Cost) / 100) * st.VATRate as VendorChargesVAT
     ,SUM(Cost) + (SUM(Cost) / 100) * st.VATRate as VendorChargesTotal
   from StockCosts sc 
   where sc.Disabled = 0
   group by sc.StockId
 ) as sc
on sc.StockId = s.StockId

我只會使用條件聚合:

select s.StockId,
       max(case when sc.ChargeType = 1 then sc.Cost else 0 end) as VendorRecovery,
       max(case when sc.ChargeType = 2 then sc.Cost else 0 end) as VendorCommission,
       sum(case when sc.Disabled = 0 then sc.Cost end) as VendorChargesNet,
       sum(case when sc.Disabled = 0 then sc.Cost / 100 end) * st.VATRate as VendorChargesVAT,
       sum(case when sc.Disabled = 0 then sc.Cost + (sc.Cost / 100) * st.VATRate end) as VendorChargesTotal
from Stock s join
     SaleTrans st 
     on st.StockId = s.StockId left join
     StockCosts sc
     on sc.StockId = s.StockId 
group by s.StockId, st.VATRate

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM