2011-03-21 80 views
1

必須有一些方法來重寫以下語句。這是醜陋的,但工程。一定有更好的方法。我想知道,所以我不會繼續使用嵌套選擇來編寫語句。重寫沒有嵌套選擇的SQL語句

輸出將是:

H45_134, 190 
H45_180, 143 

從本質上講,我試圖讓是設備訂單上所使用的不同設備和次數。在上面的輸出中,「H45_134」是設備製造編號,190是設備在訂單上使用的總次數。 190是訂單上生產線數量的總和,但僅限於設備製造編號匹配的位置。

SELECT distinct he1.[Mfg_Number] as HingeDeviceOneLocation, 
    (select sum(lineqty) 
     FROM [MQPDatabase].[dbo].[Hinge_Edge] he2 inner join lineinfo li on li.ctr=he2.lineinfoctr 
      inner join order_header oh on oh.ctr=li.order_headerctr 
      where location_1 >0 
       and location_2 =0 
       and location_3 = 0 
       and location_4=0 
       and location_5=0 
       and oh.jobnum='T35204D' 
       and he1.mfg_number=he2.mfg_number) as DeviceQty 
    FROM [MQPDatabase].[dbo].[Hinge_Edge] he1 inner join lineinfo li on li.ctr=he1.lineinfoctr 
    inner join order_header oh on oh.ctr=li.order_headerctr 
    where location_1 >0 
     and location_2 =0 
     and location_3 = 0 
     and location_4=0 
     and location_5=0 
     and oh.jobnum='T35204D' 

回答

2

試試看。

SELECT he1.[Mfg_Number] as HingeDeviceOneLocation, sum(lineqty) as DeviceQty 
    FROM [MQPDatabase].[dbo].[Hinge_Edge] he1 
    inner join lineinfo li on li.ctr=he1.lineinfoctr 
    inner join order_header oh on oh.ctr=li.order_headerctr 
    where location_1 >0 
     and location_2 =0 
     and location_3 = 0 
     and location_4=0 
     and location_5=0 
     and oh.jobnum='T35204D' 
    GROUP BY he1.[Mfg_Number] 
1

您可能需要使用Group BY和子句。沒有時間爲你弄清楚,但這就是你應該看看的東西