The code style is horrific but out of kindness (and a small challenge from Rudy) here goes ...
Your first step should be to create a function to return an attribute for any given id. Then reformat the code so it begins to make (a tiny bit of) sense. Get rid of all joins and replace with function calls to get the attribute values. When the code is working I'd ensure the original coder gets sacked for the sake of everyones sanity.
Test this function to ensure we're pulling the right attribute for any given JOB_ID. If there are multiple values for any attribute then you'll want to use @out_value = max( ATTRIBUTE_VALUE ).
Code:
create function dbo.get_attribute( @id int, @param varchar(30) ) returns varchar(80)
as
begin
declare @out_value varchar(80)
select @out_value = ATTRIBUTE_VALUE
from ADFAPP.JOB_ATTRIBUTES
where JOB_ID = @id
and ATTRIBUTE_NAME = @param
return @out_value
end
Then rewrite your original code using this function ...
Code:
select distinct JOB_ID as JobID,
case right( dbo.get_attribute(JOB_ID,'Job.MVS.JobName') , 3)
when '-JR' THEN 'Job Reprint'
when '-MR' THEN 'Mail Piece Reprint'
when '-RR' THEN 'Retain Reprint'
else 'Print'
end as Job_Name,
dbo.get_attribute(JOB_ID,'Job.Tracking') AS Job_Tracking,
dbo.get_attribute(JOB_ID,'Job.Site.Assigned') AS Appl_Nb,
int( dbo.get_attribute(JOB_ID,'Job.TotalDocs') ) AS TOTAL_DOCS,
dbo.get_attribute(JOB_ID,'Job.OrigDocs') AS ORIG_DOCS
from ADFAPP.JOB_HISTORY
where PROCESS_NAME = 'Download'
and STEP_NAME = 'Submit'
and STATE_NAME = 'Complete'
and TIME_STAMP between timestamp('2007-07-01 00:00:00.0')
and timestamp('2007-09-21 00:00:00.0')
order by Job_Name, dbo.get_attribute(JOB_ID,'Job.Site.Assigned')
I can't promise it works as I don't have your tables or a SQL Server near me.
The field ORIG_DOCS is all wrong in the original code as it goes to the attribute table but doesn't specify an attribute and then it pulls out a new field called orig - this looks very odd to me - so I guessed a bit in the above.
Mike