How can i move this Select Statement with Top - sql

I'm trying to optimize this query to use a join instead of this sub query, but with the Top 1, I'm a little confused.
SELECT
s.ItemNumber
s.ImportKey
,(
SELECT top 1 MerchandiseGroupID
FROM MerchandiseGroup mg
WHERE s.StoreDepartment = mg.Name AND c.ClientNumber = s.ClientNumber
) as MerchandiseGroupID
FROM dbo.Source s
INNER JOIN dbo.Client c on s.ClientNumber = c.ClientNumber
INNER JOIN dbo.ClientVendor cv on s.Vendor = cv.ClientVendorName
INNER JOIN dbo.TypeClientWarehouse tw on c.WarehouseCode = tw.WarehouseCode
WHERE s.ImportDate > '2014-05-15 01:00:00.000'
What I have so far:
INNER JOIN
(
SELECT
ROW_NUMBER() OVER (PARTITION BY Name ORDER BY MerchandiseGroupID asc) rnum,
MerchandiseGroupID,
Name
FROM MerchandiseGroup mg
) mhg
ON s.StoreDepartment = mg.Name AND c.ClientNumber = s.ClientNumber
WHERE s.ImportDate > '2014-05-15 01:00:00.000' AND mg.rnum = 1

I think using TOP 1 is no less optimal that turning it into a join and using ROW_NUMBER(), however if the reason you want a join is so you can get other fields from the tables then use an APPLY (Your first query has no order by with the top so I have assumed it to be the same as in your ROW_NUMBER function in the JOIN attempt):
SELECT
s.ItemNumber,
s.ImportKey,
mg.MerchandiseGroupID,
mg.Name
FROM dbo.Source s
INNER JOIN dbo.Client c on s.ClientNumber = c.ClientNumber
INNER JOIN dbo.ClientVendor cv on s.Vendor = cv.ClientVendorName
INNER JOIN dbo.TypeClientWarehouse tw on c.WarehouseCode = tw.WarehouseCode
OUTER APPLY
(
SELECT top 1 MerchandiseGroupID, Name
FROM MerchandiseGroup mg
WHERE s.StoreDepartment = mg.Name
AND c.ClientNumber = s.ClientNumber
ORDER BY MerchandiseGroupID
) mg
WHERE s.ImportDate > '2014-05-15 01:00:00.000'
This approach tends to be faster than ROW_NUMBER if you only want the top 1, it is less flexible if you want specific records though, such as the 3rd record.
Not related, but becareful when using the date format you have, even though this is the ISO standard it can still throw an error:
SET DATEFORMAT DMY;
SELECT CAST('2014-05-15 01:00:00.000' AS DATETIME);
Will give you:
Msg 242, Level 16, State 3, Line 2
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.

Related

CTE values need to insert into another table

Below query i am not able to insert common table expression select values into another table.
;WITH cte AS
(
SELECT
rd.reorderhistoryId,
rd.dateCreated,
rd.personId,
rd.reorderId,
rd.statusNo,
rd.createdBy,
r.OrganizationId
FROM
(SELECT
MIN(reorderhistoryId) AS reorderhistoryId,
MIN(personId) AS personId,
reorderId
FROM
reorderHistoryDetails
GROUP BY
reorderId) rh
INNER JOIN
reorderHistoryDetails rd ON rd.reorderhistoryId = rh.reorderhistoryId
INNER JOIN
reorderDetails r ON r.personId = rd.personId
WHERE
rd.statusNo = 1059
)
SELECT DISTINCT TOP 5
rlst.personId AS personId,
'Start Reorder Process' AS reorderStatusType,
1 AS productId,
3 AS amountPaid,
rlst.reorderId,
rlst.OrganizationId AS orgId,
rlst.createdBy,
rlst.dateCreated,
rlst.dateCreated AS timeStamp
FROM
cte rlst
INNER JOIN
doctororderall d ON rlst.personId = d.personId
AND d.productId = 1
AND YEAR(rlst.dateCreated) = YEAR(d.dateCreated)
INNER JOIN
patientdetails pd ON pd.personId = d.personId
WHERE
rlst.datecreated > '2020-09-01'
AND rlst.dateCreated <= '2021-10-06'
INSERT INTO rouletteTracking (personId, reorderStatusType, productId,
amountPaid, reorderId, orgId,
createdBy, dateCreated, timeStamp)
SELECT *
FROM cte
I'm getting this error:
Msg 208, Level 16, State 1, Line 14
Invalid object name 'cte'.
Both myself (in the comments) and Grant (in their answer) has already covered this, however, to repeat this a Common Table Expression is an expression. It's scope is limited to the scope of the statement it is define in (like other expressions). If you properly terminate your statements you'll see you have two statements above; a SELECT and an INSERT, and thus the CTE isn't defined in the second:
WITH cte AS
(SELECT rd.reorderhistoryId,
rd.dateCreated,
rd.personId,
rd.reorderId,
rd.statusNo,
rd.createdBy,
r.OrganizationId
FROM (SELECT MIN(reorderhistoryId) AS reorderhistoryId,
MIN(personId) AS personId,
reorderId
FROM reorderHistoryDetails
GROUP BY reorderId) rh --on d.personId=rh.personId
INNER JOIN reorderHistoryDetails rd ON rd.reorderhistoryId = rh.reorderhistoryId
INNER JOIN reorderDetails r ON r.personId = rd.personId
WHERE rd.statusNo = 1059)
SELECT DISTINCT TOP 5
rlst.personId AS personId,
'Start Reorder Process' AS reorderStatusType,
1 AS productId,
3 AS amountPaid,
rlst.reorderId,
rlst.OrganizationId AS orgId,
rlst.createdBy,
rlst.dateCreated,
rlst.dateCreated AS timeStamp
FROM cte rlst
INNER JOIN doctororderall d ON rlst.personId = d.personId
AND d.productId = 1
AND YEAR(rlst.dateCreated) = YEAR(d.dateCreated)
INNER JOIN patientdetails pd ON pd.personId = d.personId
WHERE rlst.datecreated > '2020-09-01'
AND rlst.dateCreated <= '2021-10-06'; --This statement ends HERE
--New statement starts here. The CTE cte has no context here.
INSERT INTO rouletteTracking (personId,
reorderStatusType,
productId,
amountPaid,
reorderId,
orgId,
createdBy,
dateCreated,
timeStamp)
SELECT *
FROM cte;
Assuming you want to SELECT the TOP (5) (arbitrary) rows first from the CTE first, and then INSERT the entire result set from the CTE into your table afterwards, I would INSERT the data into a temporary table first, and then SELECT and INSERT from that:
WITH cte AS
(SELECT rd.reorderhistoryId,
rd.dateCreated,
rd.personId,
rd.reorderId,
rd.statusNo,
rd.createdBy,
r.OrganizationId
FROM (SELECT MIN(reorderhistoryId) AS reorderhistoryId,
MIN(personId) AS personId,
reorderId
FROM reorderHistoryDetails
GROUP BY reorderId) rh --on d.personId=rh.personId
INNER JOIN reorderHistoryDetails rd ON rd.reorderhistoryId = rh.reorderhistoryId
INNER JOIN reorderDetails r ON r.personId = rd.personId
WHERE rd.statusNo = 1059)
SELECT *
INTO #Temp
FROM cte;
SELECT DISTINCT TOP 5
rlst.personId AS personId,
'Start Reorder Process' AS reorderStatusType,
1 AS productId,
3 AS amountPaid,
rlst.reorderId,
rlst.OrganizationId AS orgId,
rlst.createdBy,
rlst.dateCreated,
rlst.dateCreated AS timeStamp
FROM #Temp rlst
INNER JOIN doctororderall d ON rlst.personId = d.personId
AND d.productId = 1
AND YEAR(rlst.dateCreated) = YEAR(d.dateCreated)
INNER JOIN patientdetails pd ON pd.personId = d.personId
WHERE rlst.datecreated > '2020-09-01'
AND rlst.dateCreated <= '2021-10-06'
ORDER BY {The Column to order by}; --This statement ends HERE
--New statement starts here. The CTE cte has no context here.
INSERT INTO rouletteTracking (personId,
reorderStatusType,
productId,
amountPaid,
reorderId,
orgId,
createdBy,
dateCreated,
timeStamp)
SELECT *
FROM #Temp;
Note: I expect the INSERT statement at the end to still fail. You attempt to insert into a timestamp column (a deprecated synonym for rowversion); that isn't allowed.
The name Common Table Expression is a bit misleading. Many people read it and see the word "TABLE" very prominently. They then assume that they're dealing with a new kind of temporary table or table variable. However, the word to focus on is "EXPRESSION".
A CTE is only useable within the statement that defines it. It's not, in any way, temporary storage. It's simply a query. It's like having a sub-query to define a table like this:
SELECT *
FROM (SELECT * FROM dbo.MyTable) as NotaCTEButActsLikeOne
In order to do your process, you need to move the entire SELECT statement including your CTE into a single statement with the INSERT process.
EDIT:
Here. You just move everything so that it's a single statement:
WITH
cte AS
(SELECT rd.reorderhistoryId,
rd.dateCreated,
rd.personId,
rd.reorderId,
rd.statusNo,
rd.createdBy,
r.OrganizationId
FROM (SELECT MIN(reorderhistoryId) AS reorderhistoryId,
MIN(personId) AS personId,
reorderId
FROM reorderHistoryDetails
GROUP BY reorderId) rh --on d.personId=rh.personId
INNER JOIN reorderHistoryDetails rd ON rd.reorderhistoryId = rh.reorderhistoryId
INNER JOIN reorderDetails r ON r.personId = rd.personId
WHERE rd.statusNo = 1059)
INSERT INTO rouletteTracking (personId,
reorderStatusType,
productId,
amountPaid,
reorderId,
orgId,
createdBy,
dateCreated,
timeStamp)
SELECT DISTINCT TOP 5
rlst.personId AS personId,
'Start Reorder Process' AS reorderStatusType,
1 AS productId,
3 AS amountPaid,
rlst.reorderId,
rlst.OrganizationId AS orgId,
rlst.createdBy,
rlst.dateCreated,
rlst.dateCreated AS timeStamp
FROM cte rlst
INNER JOIN doctororderall d ON rlst.personId = d.personId
AND d.productId = 1
AND YEAR(rlst.dateCreated) = YEAR(d.dateCreated)
INNER JOIN patientdetails pd ON pd.personId = d.personId
--inner join (select min(reorderhistoryId) as reorderhistoryId,min(personId) as personId,reorderId from reorderHistoryDetails where statusNo=1059 and personId=226020 group by reorderId )as rh on d.personId=rh.personId
--inner join reorderHistoryDetails rd on rd.reorderHistoryId=rh.reorderhistoryId and rd.statusNo=1059
WHERE rlst.datecreated > '2020-09-01'
AND rlst.dateCreated <= '2021-10-06';
Also, please, the semi-colon is a statement terminator, not something you put in front of the WITH clause. Examples on line do that so that people can copy the code and it will compile (a righteous approach). However, just putting it at the end of your statements, everything will work and the code won't look awful.

Order by on a nested query

Is their a way to order this by the Time column? I am not sure how to do this. The time is the schedule and I just need it to go from the morning to the evening.
Can I just nest another select statement and use that?
Thank you.
SELECT
DoseLevel,
LastName,
FirstName,
DOB,
EMPLID,
Time,
(
SELECT v.ColorCode
FROM ABCDocumentation cd1
LEFT JOIN ABCDocumentation cd2ON cd1.ABCDocumentationID = cd2.PairID
LEFT JOIN Medicine v ON v.MedicineID = cd1.MedicineID
LEFT JOIN Manufacturers mfg ON v.MFG_Seq = mfg.MFG_Seq
WHERE cd2.ABCDocumentationID = dt.ABCDocumentationID
) AS ParentColorCode,
(
SELECT mfg.Description
FROM ABCDocumentation cd1
LEFT JOIN ABCDocumentation cd2 ON cd1.ABCDocumentationID = cd2.PairID
LEFT JOIN Medicine v ON v.MedicineID = cd1.MedicineID
LEFT JOIN Manufacturers mfg ON v.MFG_Seq = mfg.MFG_Seq
WHERE cd2.ABCDocumentationID = dt.ABCDocumentationID
) AS ParentManuDesc
FROM
(
SELECT
cd.DoseLevel,
e.LastName,
e.FirstName,
e.DOB,
cvse.EMPLID,
cvse.AdminScheduleSlotsEmployeeID,
cd.ABCDocumentationID,
cvss.Time,
cd.ModifyDate AS 'StartTime'
FROM ABCAdminSchedule cvs
LEFT JOIN ABCAdminScheduleSlots cvss ON cvs.AdminScheduleID = cvss.AdminScheduleID
LEFT JOIN ABCAdminScheduleSlotsEmployee cvse ON cvss.AdminScheduleSlotsID = cvse.AdminScheduleSlotsID
LEFT JOIN ABCDocumentation cd ON cvse.AdminScheduleSlotsEmployeeID = cd.AdminScheduleSlotsEmployeeID
LEFT JOIN Employee e ON cvse.EmplID = e.EMPLID
WHERE CAST(TIME AS Date) = CAST(GETDATE() AS Date) AND CampusID = '06'
AND cvse.AdminScheduleSlotsEmployeeID IS NOT NULL
) dt
First off, there is no need for the derived table dt, as you are not doing any further processing.
Secondly, you can combine the two correlated subqueries into one with an APPLY.
Thirdly, conversions on columns can cause performance issues, so you can change the date check to a half-open interval, converting just GETDATE().
Finally you can add at the end an ORDER BY clause to sort.
SELECT
cd.DoseLevel,
e.LastName,
e.FirstName,
e.DOB,
cvse.EMPLID,
cvss.Time,
Parent.ColorCode,
Parent.Description
FROM ABCAdminSchedule cvs
LEFT JOIN ABCAdminScheduleSlots cvss ON cvs.AdminScheduleID = cvss.AdminScheduleID
LEFT JOIN ABCAdminScheduleSlotsEmployee cvse ON cvss.AdminScheduleSlotsID = cvse.AdminScheduleSlotsID
LEFT JOIN ABCDocumentation cd ON cvse.AdminScheduleSlotsEmployeeID = cd.AdminScheduleSlotsEmployeeID
LEFT JOIN Employee e ON cvse.EmplID = e.EMPLID
OUTER APPLY
(
SELECT v.ColorCode, mfg.Description
FROM ABCDocumentation cd1
LEFT JOIN ABCDocumentation cd2ON cd1.ABCDocumentationID = cd2.PairID
LEFT JOIN Medicine v ON v.MedicineID = cd1.MedicineID
LEFT JOIN Manufacturers mfg ON v.MFG_Seq = mfg.MFG_Seq
WHERE cd2.ABCDocumentationID = dt.ABCDocumentationID
) AS Parent
WHERE TIME >= CAST(GETDATE() AS Date) AND TIME < CAST(DATEADD(day, 1, GETDATE()) AS DATE)
AND CampusID = '06'
AND cvse.AdminScheduleSlotsEmployeeID IS NOT NULL
ORDER BY TIME
please
declare #tm table (id int identity, timee time(7))
insert into #tm (timee) values ('01:05:45'),
('10:15:18'),
('14:18:59'),
('09:15:10'),
('18:19:21'),
('21:05:17')
this is a default
select * from #tm order by id
this is a, what do you need
select tm.*,
iif(tm.part_time = 1, 'morning', 'evening') m_e from (select
case
when timee between '09:00:00' and '19:00:00' then 1
else 2 end part_time,
*
from #tm) tm
order by part_time, timee

Count with row_number function SQL CTE

I have the below CTEs that work perfectly, but I want to count the "cl.memb_dim_id" by "cl.post_date" but I am not sure how to do that? When adding in the count function I get an error that highlights the ' row number' so I am assuming I cant have both order and group together ????
WITH
DATES AS
(
select to_date('01-jan-2017') as startdate,to_date('02-jan-2017') as enddate
from dual
),
Claims as (select distinct
cl.memb_dim_id,
row_number () over (partition by cl.Claim_number order by cl.post_date desc) as uniquerow,
cl.Claim_number,
cl.post_date,
ct.claim_type,
ap.claim_status_desc,
dc.company_desc,
dff.io_flag_desc,
pr.product_desc,
cl.prov_dim_id,
cl.prov_type_dim_id
from dw.fact_claim cl
inner join dates d
on 1=1
and cl.post_date >= d.startdate
and cl.post_date <= d.enddate
and cl.provider_par_dim_id in ('2')
and cl.processing_status_dim_id = '1'
and cl.company_dim_id in ('581','585','586','589','590','591','588','592','594','601','602','603','606','596','598','597','579','599','578','577','573','574','576','575')
left join dw.DIM_CLAIM_STATUS ap
on cl.claim_status_dim_id = ap.claim_status_dim_id
left join dw.dim_claim_type ct
on cl.claim_type_dim_id = ct.claim_type_dim_id
and cl.claim_type_dim_id in ('1','2','6','7')
left join dw.DIM_COMPANY dc
on cl.company_dim_id = dc.company_dim_id
left join dw.DIM_IO_FLAG dff
on cl.io_flag_dim_id = dff.io_flag_dim_id
left join dw.dim_product pr
on cl.product_dim_id = pr.product_dim_id
)
Select * from claims where uniquerow ='1'
First, does this work?
count(cl.memb_dim_id) over (partition by cl.Claim_number, cl.post_date) as cnt,
Second, it is strange to be using analytic functions with select distinct.

Limiting result sets by future date - SQL

The Query below produces a record for each Entry in the SP_ScheduleEvent Table.
SELECT m.MaterialId, m.MaterialTitle, se.EventDateTime, c.ChannelName
FROM GB_Material m
LEFT OUTER JOIN SP_ScheduleEvent se on se.MaterialName = m.MaterialName
INNER JOIN SP_Schedule s on s.ScheduleID = se.ScheduleID
INNER JOIN GB_Channel c on c.ChannelID = s.ChannelID
WHERE LOWER(m.MaterialName) like '%foo%' OR LOWER(m.MaterialTitle) like '%foo%'
I want to limit the result set by the nearest future EventDateTime.
So per material name i would like to see one EventDateTime, which should be the nearest future date to the current time.
And lastly, a record may not exist in the SP_ScheduleEvent table for a particular materialname, in which case there should be null returned for the EventDateTime column
SQLFiddle
How would i go about doing this?
First, your LEFT JOIN is immaterial, because the subsequent joins make it an INNER JOIN. Either use LEFT JOIN throughout the FROM statement or switch to INNER JOIN.
I think you can use ROW_NUMBER():
SELECT t.*
FROM (SELECT m.MaterialId, m.MaterialName, m.MaterialTitle, se.EventDateTime,
ROW_NUMBER() over (PARTITION BY m.MaterialId OVER se.EventDateTime DESC) as seqnum
FROM GB_Material m INNER JOIN
SP_ScheduleEvent se
on se.MaterialName = m.MaterialName INNER JOIN
SP_Schedule s
on s.ScheduleID = se.ScheduleID INNER JOIN
GB_Channel c
on c.ChannelID = s.ChannelID
WHERE se.EventDateTime > getdate() AND
(LOWER(m.MaterialName) like '%foo%' OR LOWER(m.MaterialTitle) like '%foo%')
) t
WHERE seqnum = 1
ORDER BY se.EventDateTime;
Use the ROW_NUMBER() function:
WITH cte AS (
SELECT m.MaterialId, m.MaterialTitle, se.EventDateTime, c.ChannelName,
ROW_NUMBER() OVER (PARTITION BY m.MaterialId ORDER BY EventDateTime ASC) AS rn
FROM GB_Material m
LEFT OUTER JOIN SP_ScheduleEvent se on se.MaterialName = m.MaterialName
LEFT OUTER JOIN SP_Schedule s on s.ScheduleID = se.ScheduleID
LEFT OUTER JOIN GB_Channel c on c.ChannelID = s.ChannelID
WHERE LOWER(m.MaterialName) like '%foo%' OR LOWER(m.MaterialTitle) like '%foo%'
AND se.EventDateTime > GETDATE()
)
SELECT * FROM cte
WHERE rn=1

SQL inner join on alias (for XML)

I have a running query where I need to expand the XML hierarchy.
The existing query does this (WORKING):
select a.fields, (select c.fields from c),
(select d.fields from d), (select e.fields from e)
from a
--REPAIR ORDERS, PARTS, LABOR, NARRATIVE
I need to create another level at b (THIS IS THE JOB ORDER FOR REPAIR ORDERS, and aliased as bb):
--REPAIR ORDERS, JOB ID (JOB ID/PARTS, JOB ID/LABOR, JOB ID/NARRATIVE)
select a.fields, select b.fields, (select c.fields from c),
(select d.fields from d), (select e.fields from e) from b)
bb
from a
so here's the code (this inner join is killing me):
(also, think as REPAIR NARRATIVES as C and once I get this going I need to add D & E)
IT's the INNER JOIN at the comments line which is stopping me:
declare #OEMDEALERCODE nvarchar(20),#SDate smalldatetime,#EDate smalldatetime,#DMxServiceROJobStatus_ReadyToInvoice int
SET #SDate = '01/01/2013'
SET #EDate = '12/31/2013'
SET #DMxServiceROJobStatus_ReadyToInvoice = dbo.[fn_DMxSysGetEnumItemValue](N'DMxServiceROJobStatus', N'ReadyToInvoice')
-- JobId hierarchy
select ff.QualifyingROX, ff.JobId, ff.JobName,
(
---------------------------------------------------------------------------------------------------
SELECT DISTINCT --REPAIR NARRATIVE
Concern, Cause, Correction, CauseMore, ConcernMore, CorrectionMore
FROM
(
SELECT DISTINCT
TOP (100) PERCENT dbo.DMXDEALERINFORMATIONTABLE.OEMDEALERCODE,
dbo.DMXSERVICEROTABLE.ROID,
dbo.DMXSERVICEROJOB.JOBID,
dbo.DMXSERVICEROJOB.STATUS,
DMXSERVICECCCSTATEMENT_1.TEXT CONCERN,
dbo.DMXSERVICECCCSTATEMENT.TEXT CAUSE,
DMXSERVICECCCSTATEMENT_2.TEXT CORRECTION,
dbo.DMXSERVICEROJOB.CUSTOMCAUSETEXT CAUSEMORE,
dbo.DMXSERVICEROJOB.CUSTOMCONCERNTEXT CONCERNMORE,
dbo.DMXSERVICEROJOB.CUSTOMCORRECTIONTEXT CORRECTIONMORE,
DMXSERVICECCCSTATEMENT_2.RECVERSION Expr5,
MAX(dbo.DMXSERVICEROJOB.RECVERSION) Expr4,
MAX(dbo.DMXSERVICECCCSTATEMENT.RECVERSION) Expr3,
MAX(DMXSERVICECCCSTATEMENT_1.RECVERSION) Expr1,
MAX(DMXSERVICECCCSTATEMENT_2.RECVERSION) Expr2
FROM dbo.DMXSERVICEROJOB (NOLOCK) INNER JOIN
dbo.DMXDEALERINFORMATIONTABLE (NOLOCK) INNER JOIN
dbo.DMXSERVICEROTABLE (NOLOCK) ON dbo.DMXDEALERINFORMATIONTABLE.PARTITION = dbo.DMXSERVICEROTABLE.PARTITION ON
dbo.DMXSERVICEROJOB.ROTABLEREF = dbo.DMXSERVICEROTABLE.RECID LEFT OUTER JOIN
dbo.DMXSERVICECCCSTATEMENT DMXSERVICECCCSTATEMENT_2 ON
dbo.DMXSERVICEROJOB.CORRECTIONREF = DMXSERVICECCCSTATEMENT_2.RECID LEFT OUTER JOIN
dbo.DMXSERVICECCCSTATEMENT ON dbo.DMXSERVICEROJOB.CAUSEREF = dbo.DMXSERVICECCCSTATEMENT.RECID LEFT OUTER JOIN
dbo.DMXSERVICECCCSTATEMENT DMXSERVICECCCSTATEMENT_1 ON
dbo.DMXSERVICEROJOB.CONCERNREF = DMXSERVICECCCSTATEMENT_1.RECID
GROUP BY dbo.DMXDEALERINFORMATIONTABLE.OEMDEALERCODE, dbo.DMXSERVICEROTABLE.ROID, dbo.DMXSERVICEROJOB.JOBID, dbo.DMXSERVICEROJOB.STATUS, DMXSERVICECCCSTATEMENT_1.TEXT, dbo.DMXSERVICECCCSTATEMENT.TEXT,
DMXSERVICECCCSTATEMENT_2.TEXT, dbo.DMXSERVICEROJOB.CUSTOMCAUSETEXT, dbo.DMXSERVICEROJOB.CUSTOMCONCERNTEXT,
dbo.DMXSERVICEROJOB.CUSTOMCORRECTIONTEXT, DMXSERVICECCCSTATEMENT_2.RECID, DMXSERVICECCCSTATEMENT_2.PARTITION,
dbo.DMXSERVICECCCSTATEMENT.RECVERSION, dbo.DMXSERVICECCCSTATEMENT.PARTITION, DMXSERVICECCCSTATEMENT_1.PARTITION,
dbo.DMXSERVICEROJOB.RECVERSION, dbo.DMXSERVICEROJOB.RECID, dbo.DMXSERVICEROJOB.PARTITION,
DMXSERVICECCCSTATEMENT_1.RECVERSION, DMXSERVICECCCSTATEMENT_1.RECID, dbo.DMXSERVICECCCSTATEMENT.RECID,
DMXSERVICECCCSTATEMENT_2.RECVERSION
having dbo.DMXDEALERINFORMATIONTABLE.OEMDEALERCODE = #OEMDEALERCODE
--and dbo.DMXSERVICEROTABLE.ROID = ff.QualifyingROX
and dbo.DMXSERVICEROJOB.STATUS=#DMxServiceROJobStatus_ReadyToInvoice
ORDER BY Expr4 DESC, Expr3 DESC, Expr1 DESC, Expr2 DESC
) cc
inner join ff on cc.ROID = ff.QualifyingROX
---------------------------------------------------------------------------------------------------
)
FROM
(
SELECT DISTINCT --REPAIR NARRATIVE
ee.JobId, ee.JobName, ee.QualifyingROX
from
(
SELECT DISTINCT TOP (100) PERCENT
dbo.DMXSERVICEROTABLE.ROID QualifyingROX,
dbo.DMXSERVICEROJOB.JOBID JobId,
MAX(DISTINCT dbo.DMXSERVICEROJOB.NAME) JobName
FROM dbo.DMXSERVICEROTABLE (nolock) INNER JOIN dbo.DMXSERVICEROJOB (NOLOCK) ON dbo.DMXSERVICEROTABLE.RECID = dbo.DMXSERVICEROJOB.ROTABLEREF
GROUP BY dbo.DMXSERVICEROTABLE.ROID, dbo.DMXSERVICEROJOB.JOBID
ORDER BY QualifyingROX, dbo.DMXSERVICEROJOB.JOBID
) ee
) ff
for XML PATH ('JobDetail'), ROOT ('Jobs'), TYPE