Rewrite SQL statement without nested select
There has to be some way to re-write the folowing statement. It's ugly, but works. There has to be a better way. I would like to know so I don't continue writing statements with nested selects.
The output would be:
H45_134, 190
H45_180, 143
Essentially, what I'm开发者_如何学JAVA trying to get are the distinct devices and the number of times that device is used on an order. In the output above, "H45_134" is the device mfg number and 190 is the total number of times the device is used on the order. 190 is the sum of the line quantity on the order, but only where the device mfg number matches.
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'
Give this a try.
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]
You probably would need to use Group BY and having clauses. Don't have time to figure them out for you but that's what you should look into
精彩评论