在没有嵌套选择的情况下重写SQL语句

时间:2011-03-21 17:15:22

标签: sql select

必须有一些方法来重写下面的陈述。这很难看,但很有效。一定有更好的方法。我想知道所以我不会继续使用嵌套选择来编写语句。

输出结果为:

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 个答案:

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

您可能需要使用Group BY并具有子句。没有时间为你解决这些问题,但这就是你应该研究的问题