Iamthestig
Programmer
Hi, I'm having trouble returning all the columns from a Grouped By Union query in SQL 2014.
I'm trying to return the most recent search closed by company. I should only return 2 records. If I add the extra columns in the Group By clause I get extra unwanted rows.
This returns the 2 most recently Closed Grouped Company Names I want.
How can I return all the other columns that are commented out?
Any guidance greatly appreciated.
I'm trying to return the most recent search closed by company. I should only return 2 records. If I add the extra columns in the Group By clause I get extra unwanted rows.
Code:
SELECT
lvl1.CompanyName,
MAX(CAST(jf.JOB_SEARCHCLOSED as date)) 'SearchClosed'
--jf.JOB_CONS1,
--jf.JOB_NUMBER,
--jf.JOB_STATUS,
--jf.JOB_NAME
FROM
tblOffLimits AS ol
INNER JOIN
tblLevel1Companies AS lvl1
ON ol.Level1CompanyID = lvl1.CompanyID
INNER JOIN tblJobFile jf
ON lvl1.CompanyCode = jf.JOB_COMPANYCODE
WHERE (ol.StartFrom = 'Completion')
AND DATEADD(month,CAST(ol.Months AS int),jf.JOB_SEARCHCLOSED) < CAST(CURRENT_TIMESTAMP AS DATE)
GROUP BY lvl1.CompanyName
UNION
SELECT
tlvl1.CompanyName,
MAX(CAST(jf.JOB_SEARCHCLOSED as date)) 'SearchClosed'
--jf.JOB_CONS1,
--jf.JOB_NUMBER,
--jf.JOB_STATUS,
--jf.JOB_NAME
FROM
tblOffLimits AS ol JOIN
tblLevel2Companies AS tlvl2
ON ol.Level2CompanyID = tlvl2.COMPANY_ID2
JOIN tblLevel1Companies AS tlvl1
ON tlvl2.Company_ID = tlvl1.COMPANYID
JOIN tblJobFile AS jf ON tlvl1.CompanyCode = jf.JOB_COMPANYCODE
WHERE ol.StartFrom = 'Completion'
AND jf.JOB_STATUS = 'C'
AND DATEADD(month,CAST(ol.Months AS int),jf.JOB_SEARCHCLOSED) < CAST(CURRENT_TIMESTAMP AS DATE)
GROUP BY tlvl1.CompanyName
This returns the 2 most recently Closed Grouped Company Names I want.
How can I return all the other columns that are commented out?
Any guidance greatly appreciated.