Order by on a nested query - sql

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

Related

SELECT subquery for dates in BETWEEN WHERE clause

I want to use dates from a different table in the BETWEEN inside the WHERE clause.
How can I inject the dates? The query below works, but is much slower than using plain dates.
I've tried rewriting the query in numerous ways, as well as use CTEs, to no avail.
Is there a way to make this work faster?
select *
from (
select
ti.*,
si.anvat as vat,
cast(si.acName as nvarchar(255)) productNameOriginal,
cast(su.acName as nvarchar(255)) unit,
cast(ss.acName2 as nvarchar(255)) supplier,
historyStart,
historyEnd
from tenderItem ti
left join the_setitem si on si.acIdent = ti.sku
left join tHE_SetUM su on su.acUM = si.acUM
left join tHE_SetSubj ss on ss.acSubject = si.acSupplier
left join tender t on t.id = ti.tenderId
where tenderId = 1
) t1
left join (
select
acident sku,
sum(anQty) historyQuantity,
round(max(anRTPrice), 2) historyPrice
from the_moveitem mi
left join the_move m on m.ackey = mi.ackey
where
m.acDocType in (
'3000'
'3050'
)
and m.acreceiver = '11111'
and m.addate
between (select historyStart from tender where id = 1) -- <------ THIS PART
and (select historyEnd from tender where id = 1) -- <------ THIS PART
group by acident
) history on history.sku = t1.sku
Managed to solve it by using variables.
DECLARE #historyStart DATE;
SET #historyStart = (select historyStart from tender where id = #tenderId);
DECLARE #historyEnd DATE;
SET #historyEnd = (select historyEnd from tender where id = #tenderId);
--
and m.addate between #historyStart and #historyEnd

Optimizing Multiple SQL Queries

I have 2 queries that I want to optimize but I don't know how. The execution time is not acceptable for me.
I'm working with jira database and did query to show different tasks with some attributes.
The code is:
SET NOCOUNT ON
DROP TABLE IF EXISTS #TT
DROP TABLE IF EXISTS #TT1
DROP TABLE IF EXISTS #TT2
SELECT DISTINCT concat(pr.[pkey], '-', ji.[issuenum]) AS 'Ключ'
,concat('https://sd.finam.ru/browse/', pr.[pkey], '-', ji.[issuenum]) AS 'Ссылка'
,p.[pname] AS 'П'
,users.[display_name] AS 'Исполнитель'
,CAST(ji.[CREATED] AS smalldatetime) AS 'Создан'
,CAST(ji.[RESOLUTIONDATE] AS smalldatetime) AS 'Дата резолюции'
,ji.[issuenum]
INTO #TT
FROM
[jiraissue] AS ji
LEFT OUTER JOIN [changegroup] AS cg ON (cg.[issueid] = ji.[id])
LEFT OUTER JOIN [changeitem] AS ci ON (ci.[groupid] = cg.[id]) AND ci.FIELDTYPE='jira' AND ci.FIELD='status'
LEFT OUTER JOIN [app_user] AS au ON (au.[user_key] = cg.[AUTHOR])
LEFT OUTER JOIN [issuetype] AS itype ON (itype.[ID] = ji.[issuetype])
LEFT OUTER JOIN [priority] AS p ON (p.[ID] = ji.[PRIORITY])
LEFT OUTER JOIN [project] AS pr ON (pr.[ID] = ji.[PROJECT])
LEFT OUTER JOIN [cwd_user] as users ON (users.[user_name] = ji.[ASSIGNEE])
WHERE cg.[CREATED] >= CONVERT(datetime, '2021-12-01') AND cg.[CREATED] <= CONVERT(datetime, '2022-01-01') and CONVERT(NVARCHAR(MAX), ci.[NEWSTRING]) = N'Done'
AND itype.pname = 'Incident'
SELECT DISTINCT concat(pr.[pkey], '-', ji.[issuenum]) AS 'Ключ'
,system_t.[NAME] AS 'Контур ИС'
,system_t_t.[NAME] AS 'Критичность системы'
INTO #TT1
FROM
[jiraissue] AS ji
LEFT OUTER JOIN [changegroup] AS cg ON (cg.[issueid] = ji.[id])
LEFT OUTER JOIN [changeitem] AS ci ON (ci.[groupid] = cg.[id]) AND ci.FIELDTYPE='jira' AND ci.FIELD='status'
LEFT OUTER JOIN [app_user] AS au ON (au.[user_key] = cg.[AUTHOR])
LEFT OUTER JOIN [issuetype] AS itype ON (itype.[ID] = ji.[issuetype])
LEFT OUTER JOIN [project] AS pr ON (pr.[ID] = ji.[PROJECT])
LEFT OUTER JOIN [customfieldvalue] AS customfv ON (customfv.[ISSUE] = ji.[ID])
LEFT OUTER JOIN [AO_8542F1_IFJ_OBJ] AS system_t ON (system_t.[ID] = substring(customfv.[STRINGVALUE], PatIndex('%[0-9]%', customfv.[STRINGVALUE]), len(customfv.[STRINGVALUE])))
LEFT OUTER JOIN [AO_8542F1_IFJ_OBJ_ATTR] AS system_attr ON (system_t.[ID] = system_attr.[OBJECT_ID])
LEFT OUTER JOIN [AO_8542F1_IFJ_OBJ_ATTR_VAL] AS system_attr_val ON (system_attr.[ID] = system_attr_val.[OBJECT_ATTRIBUTE_ID])
LEFT OUTER JOIN [AO_8542F1_IFJ_OBJ] AS system_t_t ON (system_attr_val.[REFERENCED_OBJECT_ID] = system_t_t.[ID])
WHERE cg.[CREATED] >= CONVERT(datetime, '2021-12-01') AND cg.[CREATED] <= CONVERT(datetime, '2022-01-01') and CONVERT(NVARCHAR(MAX), ci.[NEWSTRING]) = N'Done'
AND (customfv.[CUSTOMFIELD] = 21003 OR customfv.[CUSTOMFIELD] = 21005)
AND (system_t.[OBJECT_TYPE_ID] = 136 OR system_t.[OBJECT_TYPE_ID] = 303 OR system_t.[OBJECT_TYPE_ID] = 143)
AND system_attr.[OBJECT_TYPE_ATTRIBUTE_ID] = 461
AND itype.pname = 'Incident'
SELECT ji.[issuenum]
,pr_pr.[pname] AS '(project) Project'
INTO #TT2
FROM
[jiraissue] AS ji
LEFT OUTER JOIN [customfieldvalue] AS customfv ON (customfv.[ISSUE] = ji.[ID])
LEFT OUTER JOIN [project] AS pr_pr ON (pr_pr.[ID] = CAST(customfv.[NUMBERVALUE] AS BIGINT))
LEFT OUTER JOIN [changegroup] AS cg ON (cg.[issueid] = ji.[id])
LEFT OUTER JOIN [changeitem] AS ci ON (ci.[groupid] = cg.[id]) AND ci.FIELDTYPE='jira' AND ci.FIELD='status'
LEFT OUTER JOIN [app_user] AS au ON (au.[user_key] = cg.[AUTHOR])
LEFT OUTER JOIN [issuetype] AS itype ON (itype.[ID] = ji.[issuetype])
WHERE cg.[CREATED] >= CONVERT(datetime, '2021-12-01') AND cg.[CREATED] <= CONVERT(datetime, '2022-01-01') and CONVERT(NVARCHAR(MAX), ci.[NEWSTRING]) = N'Done'
AND pr_pr.[pname] is not NULL
SELECT CTE.[Ключ], CTE.[Ссылка], CTE.[П], CTE.[Исполнитель], CTE.[Создан], CTE.[Дата резолюции], CTE2.[(project) Project], CTE1.[Контур ИС], CTE1.[Критичность системы], CTE.[issuenum]
FROM #TT CTE
LEFT OUTER JOIN #TT1 CTE1 ON (CTE1.[Ключ] = CTE.[Ключ])
LEFT OUTER JOIN #TT2 CTE2 ON (CTE2.[issuenum] = CTE.[issuenum])
DROP TABLE IF EXISTS #TT
DROP TABLE IF EXISTS #TT1
DROP TABLE IF EXISTS #TT2
There will be some information for the month before last.
summary of query
The next query is:
WITH CTE AS (
SELECT concat(p.pkey,'-',i.issuenum) AS 'Ключ',
cf.cfname,
cv.textvalue,
ROW_NUMBER() OVER (PARTITION BY i.issuenum ORDER BY i.issuenum) AS RowNumber_SLA
FROM customfield cf,
customfieldvalue cv,
jiraissue i,
project p
WHERE i.project = p.id
AND cv.issue = i.id
AND cv.customfield = cf.id
AND cf.customfieldtypekey = 'com.atlassian.servicedesk:sd-sla-field'
and i.issuenum IN ()
and CHARINDEX('"succeeded":false', TEXTVALUE) >0
)
SELECT CTE.Ключ
FROM CTE
WHERE RowNumber_SLA = 1
The goal is to get tasks where SLA has been failed.
So in and i.issuenum IN () my Python script is putting issue numbers that I got through previous query.
The average execution time is 3 minutes.
So, I want optimize this too, maybe join first query.
Sorry for my English. I'm not an English-speaking person.
P. S. Changing CONVERT(NVARCHAR(MAX), ci.[NEWSTRING]) = N'Done' to ci.[NEWSTRING] = 'Done' causing the error The data types ntext and varchar are incompatible in the equal to operator. Workaround - ci.[NEWSTRING] LIKE 'Done' fixing this.
The first query must be rewrite as :
SELECT DISTINCT
concat(pr.[pkey], '-', ji.[issuenum]) AS 'Ключ',
concat('https://sd.finam.ru/browse/', pr.[pkey], '-', ji.[issuenum]) AS 'Ссылка',
p.[pname] AS 'П',
users.[display_name] AS 'Исполнитель',
CAST(ji.[CREATED] AS SMALLDATETIME) AS 'Создан',
CAST(ji.[RESOLUTIONDATE] AS SMALLDATETIME) AS 'Дата резолюции',
ji.[issuenum]
INTO #TT
FROM [jiraissue] AS ji
INNER JOIN [changegroup] AS cg ON(cg.[issueid] = ji.[id])
INNER JOIN [changeitem] AS ci ON(ci.[groupid] = cg.[id])
AND ci.FIELDTYPE = 'jira'
AND ci.FIELD = 'status'
LEFT OUTER JOIN [app_user] AS au ON(au.[user_key] = cg.[AUTHOR])
INNER JOIN [issuetype] AS itype ON(itype.[ID] = ji.[issuetype])
LEFT OUTER JOIN [priority] AS p ON(p.[ID] = ji.[PRIORITY])
LEFT OUTER JOIN [project] AS pr ON(pr.[ID] = ji.[PROJECT])
LEFT OUTER JOIN [cwd_user] AS users ON(users.[user_name] = ji.[ASSIGNEE])
WHERE cg.[CREATED] >= CONVERT(DATETIME, '2021-12-01')
AND cg.[CREATED] <= CONVERT(DATETIME, '2022-01-01')
AND ci.[NEWSTRING] = 'Done'
AND itype.pname = 'Incident';
False outer joins are converted in INNER and I have aslo eliminate the ugly CONVERT to NVARCHAR(max)
Same troubles appears in the second query...

Join CTE Tables SQL Sever

I have the below CTE table that I am joining to various employee data using clockin dates and times for each employee in the table. I need to join this table TACLO onto the CTE so that the query returns the data matched to the dates on the CTE table, however when I try inner, outer, left or right joins only the records which have a clockin on the matched days appear, but I need to see both.
How can I get this?
DECLARE #Start DATE = '2018-1-1', #End DATE = GETDATE()
;WITH
dates AS
( SELECT thedate = #Start
UNION ALL
SELECT dateadd(day,1,dates.thedate)
FROM dates
WHERE dateadd(day,1,dates.thedate) <= #End)
select distinct cast(a.DET_NUMBER as varchar) as 'Frontier ID',
e.CDN_CARD_ID,
CONCAT (a.DET_G1_NAME1,' ',a.DET_SURNAME) as 'Name',
c.POS_TITLE as 'Position',
c.POS_L3_CD as 'Department',
c.POS_L4_CD as 'Department 2',
cast(a.DET_DATE_JND as date) as 'Start Date',
cast(b.TER_DATE as date) as 'Leaving Date',
CONCAT (d.DET_G1_NAME1,' ',d.DET_SURNAME) as 'Team Manager',
f.CLO_DATE2,
min(f.CLO_TIME2) over (partition by f.CLO_DATE2,e.CDN_CARD_ID) as earliest_time,
max(f.CLO_TIME2) over (partition by f.CLO_DATE2,e.CDN_CARD_ID) as latiest_time, q.thedate
from EMDET a
left outer join EMTER b on a.DET_NUMBER = b.DET_NUMBER
left outer join EMPOS c on a.DET_NUMBER = c.DET_NUMBER
left outer join EMDET d on c.POS_MANEMPNO = d.DET_NUMBER
left outer join TACDN e on a.DET_NUMBER = e.DET_NUMBER
left outer join TACLO f on e.CDN_CARD_ID = f.CLO_CARD_NO
left outer join dates q on f.CLO_DATE2 = q.thedate
Where (b.TER_DATE is null or c.POS_END>=GETDATE()) and
c.POS_TITLE is not null and
(c.POS_END<=Cast('1992-01-01' as datetime) or c.POS_END>=GETDATE()) and q.thedate = '2019-02-13'
order by [Team Manager] asc, e.CDN_CARD_ID asc, f.CLO_DATE2 asc
OPTION (maxrecursion 0)

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.

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