On the last line, before the "from" statement, if sd.QTY_ORDERED does not equal sd.QTY_SHIP, I want to query the STOCK table and pull in the cost from the line with the MAX(most recent) RCV_DATE. Currently, I'm just pulling in the MAX cost per part number. (I'm not that great at sql yet). "cmp_pnm_auto_key_subp" is the part number key.
select sh.SO_NUMBER
, sh.DUE_DATE
, sh.OPEN_FLAG
, sh.SYSUR_NAME
, sh.cmp_cmp_auto_key
, sh.cmp_soh_auto_key
, sh.COMPLETE_SHIP
, sd.ITEM_NUMBER
, sd.COND
, sd.QTY_ORDERED
, sd.QTY_SHIP
, sd.UNIT_COST
, case when sh.cmp_cmp_auto_key = 'AP:702' then 0
when sh.cmp_cmp_auto_key = 'AP:6070' then 0
when sh.cmp_cmp_auto_key = 'AP:5095' then 0
else sd.UNIT_PRICE end as [UNIT_PRICE]
, sd.EXT_PRICE
, sd.ENTRY_DATE
, isnull(sd.NEXT_SHIP_DATE, sd.entry_date) as [Next Ship Date]
, sd.QTY_DELIVERED
, sd.QTY_INVOICED
, sd.QTY_RESERVED
, sd.SHIP_DATE
, sd.ROUTE_DESC
, sd.cmp_sod_auto_key
, sd.cmp_pnm_auto_key_subp
, sd.PN
, sh.SHIP_NAME
, CASE when sd.QTY_ORDERED = sd.QTY_SHIP then sd.UNIT_COST else L.Max_Cost end as [Cost]from SO_HEADER sh
join SO_DETAIL sd on (sh.cmp_soh_auto_key = sd.cmp_soh_auto_key)
OUTER APPLY
> (
> SELECT MAX(COST) AS Max_Cost
> FROM STOCK L
> WHERE L.cmp_pnm_auto_key_subp = sd.cmp_pnm_auto_key_subp
**> **
**> **
> ) AS Lwhere sh.ENTRY_DATE > DATEADD(yy,-2,DATEADD(yy,DATEDIFF(yy,0,GETDATE()),0))
and sh.cmp = 'AP'
and sd.route_desc = 'Part Sale'
Changing the OUTER APPLY to this only gives me null values
OUTER APPLY
(
SELECT max(RCV_DATE) as [RCV Date]
, COST AS Max_Cost
FROM STOCK L
WHERE L.cmp_pnm_auto_key_subp = sd.cmp_pnm_auto_key_subp
and Rcv_Date =(SELECT MAX(rcv_date) FROM STOCK WHERE CMP = 'ap')
group by Cost) AS L