2011-03-21 79 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和子句。没有时间为你弄清楚,但这就是你应该看看的东西