Quantcast
Channel: Transact-SQL forum
Viewing all articles
Browse latest Browse all 23857

CTW with Outer apply and using a parameter

$
0
0

I am using the query below to select all the repair jobs and then select the First invoice service date that happened after the repair.  I do not understand when i run the query wide open it does not show me the repair completion/ date combo for some serial numbers that happened in  April.  When i specify (above the date parameter at the bottom)  one of the serial numbers in question - 178 the query returns me the correct result.  I do not understand why i cant run this wide open for a given month and the result would be for all serial numbers that had a repair job within April and the next invoice date after the repair, i would say 70% rows return when ran wide open w/o the serial number parameter and during my testing i specify the specific serial number in question it brings back the correct result..  really confused...

--RepairCompletion to First invoice date after repair--
;With cte As
(
select
Row_Number() Over (Partition By c.[Document No_] Order By [DateUsed] Desc) As rn,
a.[Serial No_],
b.No_ as JobNo,
b.[Completion Date] RepairCompletion,
b.[Global Dimension 2 Code],
c.[Document No_] AS InvoiceNumber,
c.[DateUsed],
b.[Reason Code],
DATEDIFF(day,[Completion Date] ,isnull(c.[DateUsed],getdate())) as DateD
  from [Chronus$Asset] a
   join [Chronus$Job] as b on b.[Serial No_] = a.[Serial No_]
outer Apply
  (
  select top (1)
  a1.[Asset Serial No_],
  a1.[Shortcut Dimension 2 Code],
  a1.[Document No_],
  b1.[Service Date] as DateUsed
   from 
[Chronus$Sales Invoice Line] as a1  join 
[Chronus$Sales Invoice Header] as b1 on b1.[No_] = a1.[Document No_] 
left join [Chronus$Dimension Value] dv on dv.Code=b1.[Shortcut Dimension 2 Code]
  where a1.[Asset Serial No_]=a.[Serial No_]
  and [Completion Date]<=b1.[Service Date]
  and a1.[Asset Serial No_]<>''


   
  
  
  order by [DateUsed]
  ) c
  
   where 
        b.[Job Type 2] = 2 --2Repair
    and a.[Product Group] in ('Foo','Bar')

   and a.[Serial No_]='178' 
    and b.[Completion Date] >= '20130401'
   and [Completion Date] <=    '20130430'
)
   select [Serial No_], 
[Global Dimension 2 Code],
[InvoiceNumber],
[RepairCompletion],
[DateUsed],
JobNo,
DateD,
[Reason Code]
from cte
where rn = 1   

order by [Serial No_], [RepairCompletion]




Viewing all articles
Browse latest Browse all 23857

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>