Join with 2 temporary table - sql

How to create one more temporary table in below query to have join with the same.
WITH financial_move_out_due_days AS (
SELECT property_id,
management_company_id,
value
FROM property_preferences
WHERE property_id IN ( 112,332 ) AND management_company_id = 23
)
SELECT
l.id,
l.primary_customer_id,
( c.name_first || c.name_last ) AS customer_name_full,
c.email_address AS customer_email_address,
c.phone_number AS phone_number
FROM leases l
JOIN customers c ON ( c.management_company_id = l.management_company_id AND c.id = l.primary_customer_id )
JOIN financial_move_out_due_days fmpodd ON ( fmpodd.management_company_id = l.management_company_id AND fmpodd.property_id = l.property_id )
WHERE
l.management_company_id = 23
AND l.property_unit_id IS NOT NULL
AND l.unit_space_id IS NOT NULL';

Try like this:
WITH financial_move_out_due_days AS
(
SELECT property_id,
management_company_id,
value
FROM property_preferences
WHERE property_id IN ( 112,332 ) AND management_company_id = 23
),
another_financial_move_out_due_days AS
(
SELECT property_id,
management_company_id,
value
FROM property_preferences
WHERE property_id IN ( 112,332 ) AND management_company_id = 23
)
SELECT
l.id,
l.primary_customer_id,
( c.name_first || c.name_last ) AS customer_name_full,
c.email_address AS customer_email_address,
c.phone_number AS phone_number
FROM leases l
JOIN customers c ON ( c.management_company_id = l.management_company_id AND c.id = l.primary_customer_id )
JOIN financial_move_out_due_days fmpodd ON ( fmpodd.management_company_id = l.management_company_id AND fmpodd.property_id = l.property_id )
JOIN another_financial_move_out_due_days fmpodd ON ( fmpodd.management_company_id = l.management_company_id AND fmpodd.property_id = l.property_id )
WHERE
l.management_company_id = 23
AND l.property_unit_id IS NOT NULL
AND l.unit_space_id IS NOT NULL';

WITH FirstTable AS
(
),
SecondTable AS
(
),
....

Related

Parenthesis error when I add one more UNION [duplicate]

This question already has answers here:
Oracle: Order by Union returning ORA-00933: SQL command not properly ended
(3 answers)
Closed 4 months ago.
I have a subquery of another query in which I have to show a lot of data, and I wanted to add a third UNION in the query. It should be noted that before adding the third UNION the query worked without problems, but when adding the third UNION it shows me an error of
ORA-00907: missing right parenthesis
00907. 00000 - "missing right parenthesis"
The line it indicates is a parenthesis just before the third UNION, but if I add it, everything falls apart and gives an error that the query is not closing properly and thus a loop. Searching I have seen that it may be because of the order by that does not support them when there are multiple unions, but with two it already works, I do not understand it.
This is the entire subquery:
SELECT
*
FROM
(
SELECT
ROWNUM RNUM,
SUBQUERY.*
FROM
(
SELECT
SERVICES_TABLE.SERVICE_ID SESSION_SERVICE_CATALOG_ID,
MT_CES_SERVICE_LEVEL_3.TEXT_NAME_ES MT_CES_SERVICE_LEVEL_3_TEXT_NAME_ES,
MT_CES_SERVICE_LEVEL_3.TEXT_NAME_EN MT_CES_SERVICE_LEVEL_3_TEXT_NAME_EN,
MT_CES_SERVICE_LEVEL_2.TEXT_NAME_ES MT_CES_SERVICE_LEVEL_2_TEXT_NAME_ES,
MT_CES_SERVICE_LEVEL_2.TEXT_NAME_EN MT_CES_SERVICE_LEVEL_2_TEXT_NAME_EN,
MT_CES_SERVICE_LEVEL_2.ID MT_CES_SERVICE_LEVEL_2_ID,
MT_CES_SERVICE_LEVEL_1.TEXT_NAME_ES MT_CES_SERVICE_LEVEL_1_TEXT_NAME_ES,
MT_CES_SERVICE_LEVEL_1.TEXT_NAME_EN MT_CES_SERVICE_LEVEL_1_TEXT_NAME_EN,
MT_CES_SERVICE_LEVEL_1.ID MT_CES_SERVICE_LEVEL_1_ID,
MT_CES_SERVICE_LEVEL_3.ALARM_DAYS CES_CATALOG_ALARM_DAYS,
MT_CES_SERVICE_LEVEL_3.ADVANCE_DAYS CES_CATALOG_ADVANCE_DAYS,
MT_CES_SERVICE_LEVEL_3.COST_BY_STUDENT CES_CATALOG_COST_BY_STUDENT,
MT_CES_SERVICE_LEVEL_3.DESCRIPTION,
SERVICES_TABLE.COST SESSION_SERVICE_COST,
SERVICES_TABLE.NUM_ITEMS SESSION_SERVICE_NUM_ITEMS,
SERVICES_TABLE.COMMENTS SESSION_SERVICE_COMMENTS,
SERVICES_TABLE.STATUS PROGRAM_SERVICE_STATUS,
MT_CES_STATUS.TEXT_NAME_EN PROGRAM_SERVICE_STATUS_LITERAL,
(
SELECT
LISTAGG(MTP.TEXT_NAME_EN, ', ') WITHIN GROUP(
ORDER BY
MTP.TEXT_NAME_EN ASC
)
FROM
FRM.MT_CES_SERVICE_LEVEL_3_PROVIDERS P
INNER JOIN FRM.MT_CES_PROVIDER MTP
ON
(MTP.ID = P.PROVIDER_ID)
WHERE
P.MT_CES_SERVICE_LEVEL_3_ID = MT_CES_SERVICE_LEVEL_3.ID
) PROVIDER_LITERAL,
(
SELECT
LISTAGG(PRO.NAME, ', ') WITHIN GROUP(
ORDER BY
PRO.NAME ASC
)
FROM
FRM.SESIONCURSO SES
INNER JOIN FRM.AS_COURSE COU
ON
(
SES.CURSO = COU.ID AND COU.REMOVED = '0'
)
INNER JOIN FRM.AS_PERIOD PE
ON
(
COU.PERIOD_ID = PE.ID AND PE.REMOVED = '0'
)
INNER JOIN FRM.AS_PROGRAM PRO
ON
(
PE.PROGRAM_ID = PRO.ID AND PRO.REMOVED = '0'
)
WHERE
PRO.ID != AS_PROGRAM.ID AND SES.HORAINICIO = SE.HORAINICIO AND(
NVL(
SE.AULA,
(
NVL(
AS_COURSE.CLASSROOM_ID,
AS_PROGRAM.CLASSROOM_ID
)
)
)
) =(
NVL(
SES.AULA,
(
NVL(
COU.CLASSROOM_ID,
PRO.CLASSROOM_ID
)
)
)
)
) PROGRAMS_NAME,
AS_PROGRAM.PARTICIPANTS PROGRAM_PARTICIPANTS,
SE.HORAINICIO SESSION_DATE,
SE.ID SESSION_ID,
'0' IS_SPECIAL_SESSION,
SE.NOMBRE SESSION_TITLE,
SERVICES_TABLE.ID SERVICE_ID,
SERVICES_TABLE.PARTICIPANTS,
SERVICES_TABLE.CLASSROOM_ID SERVICE_CLASSROOM_ID,
SERVICES_TABLE.SERVICE_START,
SERVICES_TABLE.SERVICE_END,
(
SELECT
AUL.TEXT_CODE
FROM
FRM.MT_CLASSROOM AUL
WHERE
AUL.ID = NVL(
SE.AULA,
(
NVL(
AS_COURSE.CLASSROOM_ID,
AS_PROGRAM.CLASSROOM_ID
)
)
)
) CALCULATED_CLASSROOM,
(
SELECT
LISTAGG(MTP.TEXT_CODE, ', ') WITHIN GROUP(
ORDER BY
MTP.TEXT_CODE ASC
)
FROM
FRM.CES_SESSION_SERVICES_CLASSROOMS P
INNER JOIN FRM.MT_CLASSROOM MTP
ON
(MTP.ID = P.CLASSROOM_ID)
WHERE
P.SERVICE_ID = SERVICES_TABLE.ID
) SERVICE_CLASSROOMS,
SE.HORAINICIO +(1 / 1440 * SE.MINUTOS) SESSION_END_DATE,
AS_PROGRAM.STATUS_ID PROGRAM_STATUS_ID,
AS_PROGRAM.NAME PROGRAM_NAME,
MT_CES_SERVICE_LEVEL_3.EXT_LINK_NAME,
MT_CES_SERVICE_LEVEL_3.EXT_LINK_URI,
CASE WHEN EXISTS(
SELECT
CES_MATERIALCOORD.ID
FROM
FRM.CES_MATERIALCOORD
WHERE
CES_MATERIALCOORD.SESSIONSERVICE_ID = SERVICES_TABLE.ID
) THEN '1' ELSE '0'
END AS HASMATERIAL,
SERVICES_TABLE.PENDING_SEND
FROM
FRM.SESIONCURSO SE
INNER JOIN FRM.AS_COURSE ON
(
SE.CURSO = AS_COURSE.ID AND AS_COURSE.REMOVED = '0'
)
INNER JOIN FRM.AS_PERIOD ON
(
AS_COURSE.PERIOD_ID = AS_PERIOD.ID AND AS_PERIOD.REMOVED = '0'
)
INNER JOIN FRM.AS_PROGRAM ON
(
AS_PERIOD.PROGRAM_ID = AS_PROGRAM.ID AND AS_PROGRAM.REMOVED = '0'
)
INNER JOIN FRM.CES_SESSION_SERVICES SERVICES_TABLE
ON
(
SERVICES_TABLE.SESSION_ID = SE.ID
)
INNER JOIN FRM.MT_CES_SERVICE_LEVEL_3 ON
(
MT_CES_SERVICE_LEVEL_3.ID = SERVICES_TABLE.SERVICE_ID
)
INNER JOIN FRM.MT_CES_SERVICE_LEVEL_2 ON
(
MT_CES_SERVICE_LEVEL_2.ID = MT_CES_SERVICE_LEVEL_3.PARENT_SERVICE
)
INNER JOIN FRM.MT_CES_SERVICE_LEVEL_1 ON
(
MT_CES_SERVICE_LEVEL_1.ID = MT_CES_SERVICE_LEVEL_2.PARENT_SERVICE
)
INNER JOIN FRM.MT_CES_STATUS ON
(
MT_CES_STATUS.ID = SERVICES_TABLE.STATUS
)
LEFT JOIN FRM.MT_CES_PROVIDER ON
(
MT_CES_PROVIDER.ID = MT_CES_SERVICE_LEVEL_3.PROVIDER_ID
)
WHERE
AS_PROGRAM.ID = 'TEST'
UNION ALL
SELECT
SERVICES_TABLE.SERVICE_ID SESSION_SERVICE_CATALOG_ID,
MT_CES_SERVICE_LEVEL_3.TEXT_NAME_ES MT_CES_SERVICE_LEVEL_3_TEXT_NAME_ES,
MT_CES_SERVICE_LEVEL_3.TEXT_NAME_EN MT_CES_SERVICE_LEVEL_3_TEXT_NAME_EN,
MT_CES_SERVICE_LEVEL_2.TEXT_NAME_ES MT_CES_SERVICE_LEVEL_2_TEXT_NAME_ES,
MT_CES_SERVICE_LEVEL_2.TEXT_NAME_EN MT_CES_SERVICE_LEVEL_2_TEXT_NAME_EN,
MT_CES_SERVICE_LEVEL_2.ID MT_CES_SERVICE_LEVEL_2_ID,
MT_CES_SERVICE_LEVEL_1.TEXT_NAME_ES MT_CES_SERVICE_LEVEL_1_TEXT_NAME_ES,
MT_CES_SERVICE_LEVEL_1.TEXT_NAME_EN MT_CES_SERVICE_LEVEL_1_TEXT_NAME_EN,
MT_CES_SERVICE_LEVEL_1.ID MT_CES_SERVICE_LEVEL_1_ID,
MT_CES_SERVICE_LEVEL_3.ALARM_DAYS CES_CATALOG_ALARM_DAYS,
MT_CES_SERVICE_LEVEL_3.ADVANCE_DAYS CES_CATALOG_ADVANCE_DAYS,
MT_CES_SERVICE_LEVEL_3.COST_BY_STUDENT CES_CATALOG_COST_BY_STUDENT,
MT_CES_SERVICE_LEVEL_3.DESCRIPTION,
SERVICES_TABLE.COST SESSION_SERVICE_COST,
SERVICES_TABLE.NUM_ITEMS SESSION_SERVICE_NUM_ITEMS,
SERVICES_TABLE.COMMENTS SESSION_SERVICE_COMMENTS,
SERVICES_TABLE.STATUS PROGRAM_SERVICE_STATUS,
MT_CES_STATUS.TEXT_NAME_EN PROGRAM_SERVICE_STATUS_LITERAL,
(
SELECT
LISTAGG(MTP.TEXT_NAME_EN, ', ') WITHIN GROUP(
ORDER BY
MTP.TEXT_NAME_EN ASC
)
FROM
FRM.MT_CES_SERVICE_LEVEL_3_PROVIDERS P
INNER JOIN FRM.MT_CES_PROVIDER MTP
ON
(MTP.ID = P.PROVIDER_ID)
WHERE
P.MT_CES_SERVICE_LEVEL_3_ID = MT_CES_SERVICE_LEVEL_3.ID
) PROVIDER_LITERAL,
(
SELECT
LISTAGG(PRO.NAME, ', ') WITHIN GROUP(
ORDER BY
PRO.NAME ASC
)
FROM
FRM.SESIONESPECIAL SES
INNER JOIN FRM.AS_PROGRAM PRO
ON
(
SES.IDPROGRAMA = PRO.ID AND PRO.REMOVED = '0'
)
WHERE
PRO.ID != AS_PROGRAM.ID AND SES.HORAINICIO = SE.HORAINICIO AND(
NVL(
SE.AULA,
(AS_PROGRAM.CLASSROOM_ID)
)
) = NVL(SES.AULA, PRO.CLASSROOM_ID)
) PROGRAMS_NAME,
AS_PROGRAM.PARTICIPANTS PROGRAM_PARTICIPANTS,
SE.HORAINICIO SESSION_DATE,
SE.ID SESSION_ID,
'1' IS_SPECIAL_SESSION,
SE.NOMBRE SESSION_TITLE,
SERVICES_TABLE.ID SERVICE_ID,
SERVICES_TABLE.PARTICIPANTS,
SERVICES_TABLE.CLASSROOM_ID SERVICE_CLASSROOM_ID,
SERVICES_TABLE.SERVICE_START,
SERVICES_TABLE.SERVICE_END,
(
SELECT
AUL.TEXT_CODE
FROM
FRM.MT_CLASSROOM AUL
WHERE
AUL.ID = NVL(
SE.AULA,
AS_PROGRAM.CLASSROOM_ID
)
) CALCULATED_CLASSROOM,
(
SELECT
LISTAGG(MTP.TEXT_CODE, ', ') WITHIN GROUP(
ORDER BY
MTP.TEXT_CODE ASC
)
FROM
FRM.CES_SPECIAL_SESSION_SERVICES_CLASSROOMS P
INNER JOIN FRM.MT_CLASSROOM MTP
ON
(MTP.ID = P.CLASSROOM_ID)
WHERE
P.SERVICE_ID = SERVICES_TABLE.ID
) SERVICE_CLASSROOMS,
SE.HORAINICIO +(1 / 1440 * SE.MINUTOS) SESSION_END_DATE,
AS_PROGRAM.STATUS_ID PROGRAM_STATUS_ID,
AS_PROGRAM.NAME PROGRAM_NAME,
MT_CES_SERVICE_LEVEL_3.EXT_LINK_NAME,
MT_CES_SERVICE_LEVEL_3.EXT_LINK_URI,
CASE WHEN EXISTS(
SELECT
CES_MATERIALCOORD.ID
FROM
FRM.CES_MATERIALCOORD
WHERE
CES_MATERIALCOORD.SPECIALSESSIONSERVICE_ID = SERVICES_TABLE.ID
) THEN '1' ELSE '0'
END AS HASMATERIAL,
SERVICES_TABLE.PENDING_SEND
FROM
FRM.SESIONESPECIAL SE
INNER JOIN FRM.AS_PROGRAM ON
(
SE.IDPROGRAMA = AS_PROGRAM.ID AND AS_PROGRAM.REMOVED = '0'
)
INNER JOIN FRM.CES_SPECIAL_SESSION_SERVICES SERVICES_TABLE
ON
(
SERVICES_TABLE.SESSION_ID = SE.ID
)
INNER JOIN FRM.MT_CES_SERVICE_LEVEL_3 ON
(
MT_CES_SERVICE_LEVEL_3.ID = SERVICES_TABLE.SERVICE_ID
)
INNER JOIN FRM.MT_CES_SERVICE_LEVEL_2 ON
(
MT_CES_SERVICE_LEVEL_2.ID = MT_CES_SERVICE_LEVEL_3.PARENT_SERVICE
)
INNER JOIN FRM.MT_CES_SERVICE_LEVEL_1 ON
(
MT_CES_SERVICE_LEVEL_1.ID = MT_CES_SERVICE_LEVEL_2.PARENT_SERVICE
)
INNER JOIN FRM.MT_CES_STATUS ON
(
MT_CES_STATUS.ID = SERVICES_TABLE.STATUS
)
LEFT JOIN FRM.MT_CES_PROVIDER ON
(
MT_CES_PROVIDER.ID = MT_CES_SERVICE_LEVEL_3.PROVIDER_ID
)
WHERE
AS_PROGRAM.ID = 'TEST'
ORDER BY
SERVICE_START
DESC
,
SESSION_DATE
DESC
,
MT_CES_SERVICE_LEVEL_1_TEXT_NAME_EN
DESC
UNION ALL
SELECT
SERVICES_TABLE.SERVICE_ID SESSION_SERVICE_CATALOG_ID,
MT_CES_SERVICE_LEVEL_3.TEXT_NAME_ES MT_CES_SERVICE_LEVEL_3_TEXT_NAME_ES,
MT_CES_SERVICE_LEVEL_3.TEXT_NAME_EN MT_CES_SERVICE_LEVEL_3_TEXT_NAME_EN,
MT_CES_SERVICE_LEVEL_2.TEXT_NAME_ES MT_CES_SERVICE_LEVEL_2_TEXT_NAME_ES,
MT_CES_SERVICE_LEVEL_2.TEXT_NAME_EN MT_CES_SERVICE_LEVEL_2_TEXT_NAME_EN,
MT_CES_SERVICE_LEVEL_2.ID MT_CES_SERVICE_LEVEL_2_ID,
MT_CES_SERVICE_LEVEL_1.TEXT_NAME_ES MT_CES_SERVICE_LEVEL_1_TEXT_NAME_ES,
MT_CES_SERVICE_LEVEL_1.TEXT_NAME_EN MT_CES_SERVICE_LEVEL_1_TEXT_NAME_EN,
MT_CES_SERVICE_LEVEL_1.ID MT_CES_SERVICE_LEVEL_1_ID,
MT_CES_SERVICE_LEVEL_3.ALARM_DAYS CES_CATALOG_ALARM_DAYS,
MT_CES_SERVICE_LEVEL_3.ADVANCE_DAYS CES_CATALOG_ADVANCE_DAYS,
MT_CES_SERVICE_LEVEL_3.COST_BY_STUDENT CES_CATALOG_COST_BY_STUDENT,
MT_CES_SERVICE_LEVEL_3.DESCRIPTION,
SERVICES_TABLE.COST SESSION_SERVICE_COST,
SERVICES_TABLE.NUM_ITEMS SESSION_SERVICE_NUM_ITEMS,
SERVICES_TABLE.COMMENTS SESSION_SERVICE_COMMENTS,
SERVICES_TABLE.STATUS PROGRAM_SERVICE_STATUS,
MT_CES_STATUS.TEXT_NAME_EN PROGRAM_SERVICE_STATUS_LITERAL,
(
SELECT
LISTAGG(MTP.TEXT_NAME_EN, ', ') WITHIN GROUP(
ORDER BY
MTP.TEXT_NAME_EN ASC
)
FROM
FRM.MT_CES_SERVICE_LEVEL_3_PROVIDERS P
INNER JOIN FRM.MT_CES_PROVIDER MTP
ON
(MTP.ID = P.PROVIDER_ID)
WHERE
P.MT_CES_SERVICE_LEVEL_3_ID = MT_CES_SERVICE_LEVEL_3.ID
) PROVIDER_LITERAL,
(
SELECT
LISTAGG(PRO.NAME, ', ') WITHIN GROUP(
ORDER BY
PRO.NAME ASC
)
FROM
FRM.SESIONCURSO SES
INNER JOIN FRM.AS_COURSE COU
ON
(
SES.CURSO = COU.ID AND COU.REMOVED = '0'
)
INNER JOIN FRM.AS_PERIOD PE
ON
(
COU.PERIOD_ID = PE.ID AND PE.REMOVED = '0'
)
INNER JOIN FRM.AS_PROGRAM PRO
ON
(
PE.PROGRAM_ID = PRO.ID AND PRO.REMOVED = '0'
)
WHERE
PRO.ID != AS_PROGRAM.ID AND SES.HORAINICIO = SE.HORAINICIO AND(
NVL(
SE.AULA,
(
NVL(
AS_COURSE.CLASSROOM_ID,
AS_PROGRAM.CLASSROOM_ID
)
)
)
) =(
NVL(
SES.AULA,
(
NVL(
COU.CLASSROOM_ID,
PRO.CLASSROOM_ID
)
)
)
)
) PROGRAMS_NAME,
AS_PROGRAM.PARTICIPANTS PROGRAM_PARTICIPANTS,
SE.HORAINICIO SESSION_DATE,
SE.ID SESSION_ID,
'0' IS_SPECIAL_SESSION,
SE.NOMBRE SESSION_TITLE,
SERVICES_TABLE.ID SERVICE_ID,
SERVICES_TABLE.PARTICIPANTS,
SERVICES_TABLE.CLASSROOM_ID SERVICE_CLASSROOM_ID,
SERVICES_TABLE.SERVICE_START,
SERVICES_TABLE.SERVICE_END,
(
SELECT
AUL.TEXT_CODE
FROM
FRM.MT_CLASSROOM AUL
WHERE
AUL.ID = NVL(
SE.AULA,
(
NVL(
AS_COURSE.CLASSROOM_ID,
AS_PROGRAM.CLASSROOM_ID
)
)
)
) CALCULATED_CLASSROOM,
(
SELECT
LISTAGG(MTP.TEXT_CODE, ', ') WITHIN GROUP(
ORDER BY
MTP.TEXT_CODE ASC
)
FROM
FRM.CES_SESSION_SERVICES_CLASSROOMS P
INNER JOIN FRM.MT_CLASSROOM MTP
ON
(MTP.ID = P.CLASSROOM_ID)
WHERE
P.SERVICE_ID = SERVICES_TABLE.ID
) SERVICE_CLASSROOMS,
SE.HORAINICIO +(1 / 1440 * SE.MINUTOS) SESSION_END_DATE,
AS_PROGRAM.STATUS_ID PROGRAM_STATUS_ID,
AS_PROGRAM.NAME PROGRAM_NAME,
MT_CES_SERVICE_LEVEL_3.EXT_LINK_NAME,
MT_CES_SERVICE_LEVEL_3.EXT_LINK_URI,
CASE WHEN EXISTS(
SELECT
CES_MATERIALCOORD.ID
FROM
FRM.CES_MATERIALCOORD
WHERE
CES_MATERIALCOORD.SESSIONSERVICE_ID = SERVICES_TABLE.ID
) THEN '1' ELSE '0'
END AS HASMATERIAL,
SERVICES_TABLE.PENDING_SEND
FROM
FRM.SESIONCURSO SE
INNER JOIN FRM.AS_COURSE ON
(
SE.CURSO = AS_COURSE.ID AND AS_COURSE.REMOVED = '0'
)
INNER JOIN FRM.AS_PERIOD ON
(
AS_COURSE.PERIOD_ID = AS_PERIOD.ID AND AS_PERIOD.REMOVED = '0'
)
INNER JOIN FRM.AS_PROGRAM ON
(
AS_PERIOD.PROGRAM_ID = AS_PROGRAM.ID AND AS_PROGRAM.REMOVED = '0'
)
INNER JOIN FRM.CES_SESSION_SERVICES SERVICES_TABLE
ON
(
SERVICES_TABLE.SESSION_ID = SE.ID
)
INNER JOIN FRM.MT_CES_SERVICE_LEVEL_3 ON
(
MT_CES_SERVICE_LEVEL_3.ID = SERVICES_TABLE.SERVICE_ID
)
INNER JOIN FRM.MT_CES_SERVICE_LEVEL_2 ON
(
MT_CES_SERVICE_LEVEL_2.ID = MT_CES_SERVICE_LEVEL_3.PARENT_SERVICE
)
INNER JOIN FRM.MT_CES_SERVICE_LEVEL_1 ON
(
MT_CES_SERVICE_LEVEL_1.ID = MT_CES_SERVICE_LEVEL_2.PARENT_SERVICE
)
INNER JOIN FRM.MT_CES_STATUS ON
(
MT_CES_STATUS.ID = SERVICES_TABLE.STATUS
)
LEFT JOIN FRM.MT_CES_PROVIDER ON
(
MT_CES_PROVIDER.ID = MT_CES_SERVICE_LEVEL_3.PROVIDER_ID
)
WHERE
SE.ID IN(
SELECT
SES.ID
FROM
FRM.SESIONCURSO SES
INNER JOIN FRM.AS_COURSE COU
ON
(
SES.CURSO = COU.ID AND COU.REMOVED = '0'
)
INNER JOIN FRM.AS_PERIOD PE
ON
(
COU.PERIOD_ID = PE.ID AND PE.REMOVED = '0'
)
INNER JOIN FRM.AS_PROGRAM PRO
ON
(
PE.PROGRAM_ID = PRO.ID AND PRO.REMOVED = '0'
)
WHERE
SES.HORAINICIO =(
SELECT
SES2.HORAINICIO
FROM
FRM.SESIONCURSO SES2
WHERE
SES2.ID = 'TEST'
) AND(
NVL(
SES.AULA,
(
NVL(
COU.CLASSROOM_ID,
PRO.CLASSROOM_ID
)
)
) =(
SELECT
NVL(
SES2.AULA,
(
NVL(
COU2.CLASSROOM_ID,
PRO2.CLASSROOM_ID
)
)
)
FROM
FRM.SESIONCURSO SES2
INNER JOIN FRM.AS_COURSE COU2
ON
(
SES2.CURSO = COU2.ID AND COU2.REMOVED = '0'
)
INNER JOIN FRM.AS_PERIOD PE2
ON
(
COU2.PERIOD_ID = PE2.ID AND PE2.REMOVED = '0'
)
INNER JOIN FRM.AS_PROGRAM PRO2
ON
(
PE2.PROGRAM_ID = PRO2.ID AND PRO2.REMOVED = '0'
)
WHERE
SES2.ID = 'TEST'
)
)
)
) SUBQUERY
WHERE
ROWNUM <= 1000
)
WHERE
RNUM > 0;
It is about the ORDER BY clause; you can't sort each select statement separately, but the whole result set.
No:
select * from
(select first_query
from some_table
order by whatever --> this can't be here
UNION ALL
select second_query
from another_table
)
where some_condition;
Yes #1:
select * from
(select first_query
from some_table
UNION ALL
select second_query
from another_table
)
where some_condition
order by whatever; --> should be here
Yes #2:
select * from
(select first_query
from some_table
UNION ALL
select second_query
from another_table
order by whatever --> should be here
)
where some_condition

simplify simple query sql

Can someone help me simplify the following query into one line .
SELECT
LL_ID,
LL_VOORNAAM,
LB_VAN_VAN,
LB_VAN_TOT,
LB_VAN_ID,
LB_VAN_INUIT_FK,
LB_NAAR_INUIT_FK,
iu_vorigeinuit_fk,
iu_id,
LB_NAAR_ID,
LB_NAAR_VAN,
LB_NAAR_TOT
FROM
LEERLING
INNER JOIN INUIT ON (LL_ID = IU_LEERLING_FK)
INNER JOIN (
SELECT
LB_ID AS LB_VAN_ID,
LB_VAN AS LB_VAN_VAN,
LB_TOT AS LB_VAN_TOT,
LB_INUIT_FK AS LB_VAN_INUIT_FK
FROM
LOOPBAAN
) AS LOOPBAAN_VAN ON (
(IU_ID = LB_VAN_INUIT_FK)
)
INNER JOIN (
SELECT
LB_ID AS LB_NAAR_ID,
LB_VAN AS LB_NAAR_VAN,
LB_TOT AS LB_NAAR_TOT,
LB_INUIT_FK AS LB_NAAR_INUIT_FK
FROM
LOOPBAAN
) AS LOOPBAAN_NAAR ON (
(iu_id = LB_NAAR_INUIT_FK)
)
WHERE
(LB_VAN_ID <> LB_NAAR_ID)
AND (
LB_NAAR_VAN = DATEADD(1 DAY TO LB_VAN_TOT)
)
and LL_ID in (41366)
order by
ll_naam
Currently, I'm getting three repeated values which I want to merge into one. See the result I would like to have.
note : "Van" means From and "naar" To
This did it for me...
) AS LOOPBAAN_VAN ON ((IU_VORIGEINUIT_FK = LB_VAN_INUIT_FK) )
SELECT
LL_ID,
LL_VOORNAAM,
LB_VAN_VAN,
LB_VAN_TOT,
LB_VAN_ID,
LB_VAN_INUIT_FK,
LB_NAAR_INUIT_FK,
iu_vorigeinuit_fk,
iu_id,
LB_NAAR_ID,
LB_NAAR_VAN,
LB_NAAR_TOT
FROM
LEERLING
INNER JOIN INUIT ON (LL_ID = IU_LEERLING_FK)
INNER JOIN (
SELECT
LB_ID AS LB_VAN_ID,
LB_VAN AS LB_VAN_VAN,
LB_TOT AS LB_VAN_TOT,
LB_INUIT_FK AS LB_VAN_INUIT_FK
FROM
LOOPBAAN
) AS LOOPBAAN_VAN ON ((IU_VORIGEINUIT_FK = LB_VAN_INUIT_FK) )
INNER JOIN (
SELECT
LB_ID AS LB_NAAR_ID,
LB_VAN AS LB_NAAR_VAN,
LB_TOT AS LB_NAAR_TOT,
LB_INUIT_FK AS LB_NAAR_INUIT_FK
FROM
LOOPBAAN
) AS LOOPBAAN_NAAR ON (( iu_id = LB_NAAR_INUIT_FK))
WHERE
(LB_VAN_ID <> LB_NAAR_ID)
AND (
LB_NAAR_VAN = DATEADD(1 DAY TO LB_VAN_TOT) )
and
LL_ID in (41366)
order by ll_naam

Slow running query of view

I have a view that summarizes calendar specific data, it is constantly showing performance issues and creating help desk tickets from customers.
We had a DBA on staff for a short time but he never showed up to work so was let go. This has largely been a developer managed database. I have run Brent Ozar's Sps (sp_BlitzFirst) and the queries to this view constantly have the highest cost.
Query Plan: https://www.brentozar.com/pastetheplan/?id=ry8Lo6T74
view code
SELECT
rae.ResourceAvailabilityExceptEventId AS MasterEventEntityId,
me.MasterEventId AS MasterEventId,
null AS ParentEventId,
me.MasterEventBillingInfoId AS MasterEventBillingInfoId,
0 AS HasScheduledParentEvent,
me.Subject AS EventSubject,
me.Description AS EventDescription,
me.EventStartDate AS EventStartDate,
me.EventEndDate AS EventEndDate,
me.TimeZone AS TimeZone,
mebi.TotalBillAmount AS BillAmount,
null AS CancelledReason,
null AS HasDiagnosis,
null AS ParticipantAuthorizationId,
null AS AuthorizationNumber,
null AS AuthorizationDescription,
null AS BillingSourceName,
null AS BillingSourceTypeId,
me.EventTypeId AS EventTypeId,
cet.Description AS EventType,
me.EventSubTypeId AS EventSubTypeId,
cest.Description AS EventSubType,
1 AS IsTimeOff,
0 AS IsInsurance,
CASE WHEN me.MasterEventBillingInfoId is null THEN 0 ELSE 1 END AS IsBillable,
0 AS IsScheduled,
0 AS IsCompleted,
0 AS IsRecurring,
0 AS IsLinkedEvent,
null AS ChildEventTypeId,
null AS ChildEventType,
'timeoff' AS EventStatus,
null AS EventStatusId,
null AS WorkflowStatusId,
null AS WorkflowStatusDescription,
ra.LinkId AS LinkId,
ra.EntityId AS EntityId,
IIF(ra.EntityId = 'E32955F7-1CE8-46A1-98D3-06A69FA4B29E',1,0) AS IsAssignedParticipant,
IIF(ra.EntityId = '173F0473-747A-48F6-B7E8-06948370AAF8',1,0) AS IsAssignedEmployee,
par.PersonId AS ParticipantId,
emp.PersonId AS AssignedEmployeeId,
null AS BillUnderEmployeeId,
null AS SupervisorEmployeeId,
par.FirstName AS ParticipantFirstName,
par.LastName AS ParticipantLastName,
emp.FirstName AS AssignedEmployeeFirstName,
emp.LastName AS AssignedEmployeeLastName,
null AS BillUnderEmployeeFirstName,
null AS BillUnderEmployeeLastName,
null AS SupervisorEmployeeFirstName,
null AS SupervisorEmployeeLastName,
null AS CredentialId,
null AS CredentialName,
me.LocationId AS LocationId,
o.Name AS Location,
0 AS PublishedScoreSheetCount,
0 AS SessionCount,
0 AS AuthItemCount,
null AS BillCodes,
pstat.Description AS PayrollStatus,
me.PayrollStatusId AS PayrollStatusId,
me.PayrollLastExportDate AS PayrollLastExportDate,
me.PayCodeId AS PayCodeId,
pc.Name AS PayCodeName
FROM Data.MasterEvent me
JOIN Data.ResourceAvailabilityExceptEvent rae WITH ( NOLOCK ) ON me.MasterEventId = rae.ResourceAvailabilityExceptEventId
JOIN Data.ResourceAvailability ra WITH ( NOLOCK ) ON rae.ResourceAvailabilityId = ra.ResourceAvailabilityId AND ra.IsSoftDeleted = 0
JOIN Mgr.Code cet WITH ( NOLOCK ) on cet.CodeId = me.EventTypeId
LEFT JOIN Mgr.Code cest WITH ( NOLOCK ) on cest.CodeId = me.EventSubTypeId
LEFT JOIN Data.MasterEventBillingInfo mebi WITH ( NOLOCK ) on me.MasterEventBillingInfoId = mebi.MasterEventBillingInfoId
LEFT JOIN Data.Person emp WITH ( NOLOCK ) on ra.LinkId = emp.PersonId AND ra.EntityId = '173F0473-747A-48F6-B7E8-06948370AAF8'
LEFT JOIN Data.Person par WITH ( NOLOCK ) on ra.LinkId = par.PersonId AND ra.EntityId = 'E32955F7-1CE8-46A1-98D3-06A69FA4B29E'
LEFT JOIN Data.Organization o WITH ( NOLOCK ) ON o.OrganizationId = me.LocationId AND o.IsSoftDeleted = 0
LEFT JOIN Mgr.Code pstat WITH ( NOLOCK ) on pstat.CodeId = me.PayrollStatusId
LEFT JOIN Data.PayCode pc WITH(NOLOCK) on pc.PayCodeId = me.PayCodeId
WHERE me.IsSoftDeleted = 0
UNION
SELECT
mee.MasterEventEntityId,
mee.MasterEventId,
me.ParentEventId,
me.MasterEventBillingInfoId,
CASE WHEN separent.ScheduledEventId is null THEN 0 ELSE 1 END as HasScheduledParentEvent,
me.Subject as EventSubject,
me.Description as EventDescription,
me.EventStartDate,
me.EventEndDate,
me.TimeZone,
mebi.TotalBillAmount AS BillAmount,
COALESCE(se.CancelledReason,sece.CancelledReason,null) AS CancelledReason,
IIF(egb.DiagnosisCodes IS NOT NULL,1,0) AS HasDiagnosis,
mebi.ParticipantAuthorizationId,
auth.AuthorizationNumber,
auth.Description as AuthorizationDescription,
billsrccmp.Name as BillingSourceName,
billsrc.BillingSourceTypeId,
me.EventTypeId,
cet.Description as EventType,
me.EventSubTypeId,
cest.Description as EventSubType,
0 AS IsTimeOff,
CASE
WHEN billsrc.BillingSourceTypeId = 'CCBDBCFC-2225-4511-B617-190430D1897C' THEN 1
else 0 END as IsInsurance,
CASE WHEN me.MasterEventBillingInfoId is null THEN 0 ELSE 1 END as IsBillable,
CASE WHEN se.ScheduledEventId is null THEN 0 ELSE 1 END as IsScheduled,
CASE WHEN ce.CompletedEventId is null THEN 0 ELSE 1 END as IsCompleted,
CASE WHEN se.ScheduleRecurrenceId is null THEN 0 ELSE 1 END as IsRecurring,
IIF(meparent.EventTypeId = '7d881908-d373-43eb-a550-ca5e6b55137c', 0, 1) IsLinkedEvent,
pevstat.EventTypeId as ChildEventTypeId,
pevstat.EventType as ChildEventType,
COALESCE(pevstat.EventStatus, evstat.EventStatus) as EventStatus,
ce.EventStatusId,
ce.WorkflowStatusId,
ceC.Description,
mee.LinkId,
mee.EntityId,
IIF(mee.LinkId = par.ParticipantId, 1, 0) as IsAssignedParticipant,
IIF(mee.LinkId = me.AssignedEmployeeId, 1, 0) as IsAssignedEmployee,
par.ParticipantId,
aemp.EmployeeId as AssignedEmployeeId,
buemp.EmployeeId as BillUnderEmployeeId,
semp.EmployeeId as SupervisorEmployeeId,
pperson.FirstName as ParticipantFirstName,
pperson.LastName as ParticipantLastName,
aeperson.FirstName as AssignedEmployeeFirstName,
aeperson.LastName as AssignedEmployeeLastName,
bueperson.FirstName as BillUnderEmployeeFirstName,
bueperson.LastName as BillUnderEmployeeLastName,
seperson.FirstName as SupervisorEmployeeFirstName,
seperson.LastName as SupervisorEmployeeLastName,
c.CredentialId,
c.Name as CredentialName,
me.LocationId,
o.Name AS Location,
COALESCE(sss.ScheduledScoreSheetCount, css.CompletedScoreSheetCount, 0) as PublishedScoreSheetCount,
COALESCE(sss.ScheduledSessionCount, css.CompletedSessionCount, 0) as SessionCount,
aai.ApptAuthItemCount as AuthItemCount,
bc.BillCodes,
pstat.Description as PayrollStatus,
me.PayrollStatusId,
me.PayrollLastExportDate,
pc.PayCodeId,
pc.Name AS PayCodeName
FROM Data.MasterEventEntity mee WITH ( NOLOCK )
JOIN Data.MasterEvent me WITH ( NOLOCK ) on mee.MasterEventId = me.MasterEventId AND me.IsSoftDeleted = 0
JOIN Views.EventStatus evstat on evstat.MasterEventId = me.MasterEventId
LEFT JOIN Data.Organization o WITH ( NOLOCK ) ON o.OrganizationId = me.LocationId AND o.IsSoftDeleted = 0
LEFT JOIN Views.EventGroupingBase egb on egb.MasterEventId = mee.MasterEventId
LEFT JOIN Data.ScheduledEvent se WITH ( NOLOCK ) on se.ScheduledEventId = me.MasterEventId
LEFT JOIN Data.CompletedEvent ce WITH ( NOLOCK ) on ce.CompletedEventId = me.MasterEventId
LEFT JOIN Mgr.Code ceC WITH ( NOLOCK ) on ce.WorkflowStatusId = ceC.CodeId
LEFT JOIN Data.ScheduledEvent sece WITH ( NOLOCK ) on sece.ScheduledEventId = ce.ScheduledEventId
JOIN Mgr.Code cet WITH ( NOLOCK ) on cet.CodeId = me.EventTypeId
LEFT JOIN Mgr.Code cest WITH ( NOLOCK ) on cest.CodeId = me.EventSubTypeId
LEFT JOIN Data.MasterEvent meparent WITH ( NOLOCK ) on meparent.MasterEventId = me.ParentEventId
LEFT JOIN Data.ScheduledEvent separent WITH ( NOLOCK ) on separent.ScheduledEventId = me.ParentEventId
LEFT JOIN Views.ParentEventStatus pevstat on me.EventTypeId = '7d881908-d373-43eb-a550-ca5e6b55137c' AND pevstat.MasterEventId = me.MasterEventId
LEFT JOIN Data.MasterEventBillingInfo mebi WITH ( NOLOCK ) on mebi.MasterEventBillingInfoId = me.MasterEventBillingInfoId and mebi.IsSoftDeleted = 0
LEFT JOIN Mgr.Code pstat WITH ( NOLOCK ) on pstat.CodeId = me.PayrollStatusId
LEFT JOIN Data.PayCode pc WITH(NOLOCK) on pc.PayCodeId=me.PayCodeId
LEFT JOIN Data.Participant par WITH ( NOLOCK ) on par.ParticipantId = COALESCE(mebi.ParticipantId, mee.LinkId)
LEFT JOIN Data.Person pperson WITH ( NOLOCK ) on pperson.PersonId = par.ParticipantId and pperson.IsSoftDeleted = 0
LEFT JOIN Data.Employee buemp WITH ( NOLOCK ) on buemp.EmployeeId = mebi.BillUnderEmployeeId
LEFT JOIN Data.Person bueperson WITH ( NOLOCK ) on bueperson.PersonId = buemp.EmployeeId and bueperson.IsSoftDeleted = 0
LEFT JOIN Data.Employee aemp WITH ( NOLOCK ) on aemp.EmployeeId = me.AssignedEmployeeId
LEFT JOIN Data.Person aeperson WITH ( NOLOCK ) on aeperson.PersonId = aemp.EmployeeId and aeperson.IsSoftDeleted = 0
LEFT JOIN Data.Credential c WITH ( NOLOCK ) on c.CredentialId = mebi.CredentialId and c.IsSoftDeleted = 0
LEFT JOIN Data.Employee semp WITH ( NOLOCK ) on semp.EmployeeId = mebi.SupervisorEmployeeId
LEFT JOIN Data.Person seperson WITH ( NOLOCK ) on seperson.PersonId = semp.EmployeeId and seperson.IsSoftDeleted = 0
LEFT JOIN Data.ParticipantAuthorization auth WITH ( NOLOCK ) on auth.ParticipantAuthorizationId = mebi.ParticipantAuthorizationId and auth.IsSoftDeleted = 0
LEFT JOIN Data.Contract authContract WITH ( NOLOCK ) on authContract.ContractId = auth.ContractId and authContract.IsSoftDeleted = 0
LEFT JOIN Data.BillingSource billsrc WITH ( NOLOCK ) on billsrc.BillingSourceId = authContract.BillingSourceId
LEFT JOIN Data.Company billsrccmp WITH ( NOLOCK ) on billsrccmp.CompanyId = billsrc.BillingSourceId and billsrccmp.IsSoftDeleted = 0
LEFT JOIN Data.InvoiceCharge ic WITH ( NOLOCK ) on ic.CompletedEventId = me.MasterEventId and ic.InvoiceChargeStatusId != 'A2D34290-8630-4735-ACCF-E08D3D1A9480' and ic.IsSoftDeleted = 0
LEFT JOIN Data.Invoice inv WITH ( NOLOCK ) on ic.InvoiceId = inv.InvoiceId and inv.IsSoftDeleted = 0
LEFT JOIN (SELECT
MasterEventBillingInfoId,
count(AuthorizationItemId) ApptAuthItemCount
FROM Data.MasterEventBillingInfoAuthItem mebiai WITH ( NOLOCK )
WHERE mebiai.IsSoftDeleted = 0
GROUP BY mebiai.MasterEventBillingInfoId) aai ON aai.MasterEventBillingInfoId = mebi.MasterEventBillingInfoId
LEFT JOIN (
SELECT
mbi2.MasterEventBillingInfoId,
STUFF((
SELECT ',' + CONCAT(bc.Name,
IIF(caeai.Modifier1 != '', CONCAT('-', caeai.Modifier1), ''),
IIF(caeai.Modifier2 != '', CONCAT(' ', caeai.Modifier2), ''),
IIF(caeai.Modifier3 != '', CONCAT(' ', caeai.Modifier3), ''),
IIF(caeai.Modifier4 != '', CONCAT(' ', caeai.Modifier4), ''))
FROM Data.MasterEventBillingInfoAuthItem caeai WITH ( NOLOCK )
JOIN Data.AuthorizationItem ai WITH ( NOLOCK ) ON caeai.AuthorizationItemId = ai.AuthorizationItemId AND ai.IsSoftDeleted = 0
JOIN Data.FeeScheduleItem fsi WITH ( NOLOCK ) ON ai.FeeScheduleItemId = fsi.FeeScheduleItemId AND fsi.IsSoftDeleted = 0
JOIN Data.BillCode bc WITH ( NOLOCK ) ON bc.BillCodeId = fsi.BillCodeId AND bc.IsSoftDeleted = 0
WHERE mbi2.MasterEventBillingInfoId = caeai.MasterEventBillingInfoId AND caeai.IsSoftDeleted = 0
ORDER BY bc.Name
FOR XML PATH ('')), 1, 1, '') AS BillCodes
FROM Data.MasterEventBillingInfo mbi2 WITH ( NOLOCK )
) bc ON bc.MasterEventBillingInfoId = mebi.MasterEventBillingInfoId
LEFT JOIN (SELECT
s.ScheduledEventId,
count(s.ScoreSheetId) ScheduledScoreSheetCount,
count(SessionId) ScheduledSessionCount
FROM Data.ScheduledEventScoreSheet s WITH ( NOLOCK )
left join Data.DataSheet ds on s.ScoreSheetId = ds.DataSheetId
WHERE s.IsSoftDeleted = 0 AND ds.DefinitionFinishedDate IS NOT NULL AND ds.CompletionDate IS NULL
GROUP BY s.ScheduledEventId) sss ON sss.ScheduledEventId = me.MasterEventId
LEFT JOIN (SELECT
s.CompletedEventId,
count(ScoreSheetId) CompletedScoreSheetCount,
count(SessionId) CompletedSessionCount
FROM Data.CompletedEventScoreSheet s WITH ( NOLOCK )
WHERE s.IsSoftDeleted = 0
GROUP BY s.CompletedEventId) css ON css.CompletedEventId = me.MasterEventId
WHERE mee.ShowOnCalendar = 1 AND mee.IsSoftDeleted = 0
I need some direction on what I can do, even if it is just recommendations on some good reliable DBA consultants I can bring in.
It might be not the only one big problem, but it looks like you have Key Lookup for 7K values in MasterEventBillingInfoAuthItem table and 300 Lookups in MasterEvent table. Review indexing on these tables.

SQL Server - get rid of derived query in join

I'm interested in some suggestions with examples on how to 1)get rid of the derived query in the left outer join and 2)remove/consolidate the cte cteSecType in the code below The derived query in the join chooses the minimum assistant_personnel_number out of a list; there can be multiple primary and backup assistants associated with an employee . thx
WITH cteAssistants ( executive_personnel_number, assistant_personnel_number, assistant_type, assign_role )
AS ( SELECT CASE WHEN ISNUMERIC(JP.XA_asgn_emplid) = 1
THEN JP.XA_asgn_emplid
ELSE ''
END AS executive_personnel_number ,
JAP.emplid AS assistant_personnel_number ,
LAT1.FIELDVALUE AS assistant_type ,
LAT3.xlatshortname AS assign_role
FROM dbo.XA_ASGN_PRNT AS KAP
LEFT OUTER JOIN dbo.XA_ASSIGNMENTS AS KA ON JP.emplid = JAP.emplid
AND JP.effdt = JAP.effdt
LEFT OUTER JOIN dbo.XA_EMPLOYEES AS EXECT ON EXECT.EMPLID = JP.XA_ASGN_EMPLID
LEFT OUTER JOIN dbo.XA_EMPLOYEES AS ASST ON ASST.EMPLID = JAP.EMPLID
LEFT OUTER JOIN dbo.XLATITEM AS XLAT1 ON LAT1.fieldname = 'XA_ASGN_TYPE'
AND LAT1.fieldvalue = JAP.XA_asgn_type
LEFT OUTER JOIN dbo.XLATITEM AS XLAT3 ON LAT3.fieldname = 'XA_ASGN_ROLE'
AND LAT3.fieldvalue = JP.XA_asgn_role
WHERE JAP.effdt = ( SELECT MAX(effdt)
FROM dbo.XA_ASGN_PRNT
WHERE emplid = JAP.emplid
AND effdt <= GETDATE()
)
--Return data only when both executive and assistant are still active; null is for Floaters
AND ( EXECT.HR_STATUS = 'A'
OR EXECT.HR_STATUS IS NULL
)
AND ASST.HR_STATUS = 'A'
AND ( JAP.XA_asgn_type = 'F'
OR ( JAP.XA_asgn_type IN ( 'A', 'AF' )
AND JP.XA_asgn_person = 'Y'
)
)
),
cteSecType ( assistant_personnel_number, SecType )
AS ( SELECT assistant_personnel_number ,
assistant_type AS SecType
FROM cteAssistants
GROUP BY assistant_type ,
assistant_personnel_number
)
SELECT EMP.XA_NETWORK_ID AS network_id ,
EMP.XA_EMPLID AS empid ,
EMP.XA_EMPLID AS employeeNumber ,
EMP.XA_FIRST_NAME AS first_name ,
EMP.XA_LAST_NAME AS last_name ,
SECRES.SecType AS SecType ,
AsstInfo.XA_fml_pref_name AS PrimaryAssistant_FML ,
AsstInfo.XA_network_id AS PrimaryAssistant_Newtork_ID ,
AsstInfo.XA_EMPLID AS PrimaryAssistant_EmpID ,
AsstInfo.XA_phone_ext AS PrimaryAssitant_Extension
FROM dbo.XA_EMPLOYEES AS EMP
LEFT OUTER JOIN dbo.XA_EMPLOYEES AS MGR ON EMP.supervisor_id = MGR.emplid
LEFT OUTER JOIN cteSecType AS SECRES ON CAST(CAST(SECRES.assistant_personnel_number AS INT) AS VARCHAR(11)) = EMP.XA_EMPLID
LEFT OUTER JOIN ( SELECT executive_personnel_number AS AttorneyID ,
MIN(assistant_personnel_number) AS AssistantID
FROM cteEmployeeAssistants AS A
WHERE ( assign_role = 'Primary' )
GROUP BY executive_personnel_number
) AS ASST ON ASST.AttorneyID = EMP.XA_EMPLID
LEFT OUTER JOIN dbo.XA_EMPLOYEES AS ASSTINFO ON ASSTINFO.XA_EMPLID = ASST.AssistantID
WHERE ( EMP.HR_STATUS = 'A' )
AND ( EMP.PER_ORG IN ( 'EMP', 'CWR' ) )
AND ( ISNULL(EMP.XA_NETWORK_ID, '') <> '' )
GO

Sql Server - 2 queries executed together takes longer

I have 2 queries.
Query # 1: inserts some data into a temp table
Query # 2: inserts the data from the temp table (with some joins) into a new table.
Running Query #1 alone takes 3 seconds. Running Query #2 alone takes 12 seconds.
When I run them both together as one execution, it runs forever (over 4 minutes).
What could possibly be the reason for this?
(I would post my code but it's very long and not much understandable to the outsider.)
Here's my SQL (at your own risk): Remember they run fine when ran alone.
-- START QUERY #1
SELECT * INTO #TempProdForSiteGoingTrim
FROM
(
SELECT
p.idProduct
, p.active
, p.sku
, p.description
, p.listprice
, p.price
, p.imageurl
, p.smallimageurl
, p.idManufacturer
, sortOrder
, CASE WHEN p.pgroup = '' OR p.pgroup IS NULL THEN CAST(p.idProduct AS VARCHAR) ELSE pgroup END [pgroup]
, CASE WHEN pa2.attr IS NULL THEN CAST(p.idProduct AS VARCHAR) ELSE CASE WHEN p.pgroup = '' OR p.pgroup IS NULL THEN CAST(p.idProduct AS VARCHAR) ELSE pgroup END END [RugGroup]
, pa1.attr [Color]
, pa3.attr [Collection]
, pa2.attr [RugSize]
, pa4.attr[RugShape]
FROM
(SELECT DISTINCT idProduct FROM ProdSite WHERE idSite = 39 ) s
INNER JOIN (SELECT * FROM products p WHERE active = -1 ) p ON s.idproduct = p.idproduct
LEFT OUTER JOIN (SELECT t.idproduct, attr FROM (SELECT max(idprodattr) [idprodattr], idproduct, b.idattrset FROM productattr a JOIN product_attr b on a.idattr = b.idattr WHERE idattrset = 1 GROUP BY a.idproduct, b.idattrset )t JOIN productattr a ON t.idprodattr = a.idprodattr JOIN product_attr b ON a.idattr = b.idattr) pa1 ON p.idproduct = pa1.idproduct
LEFT OUTER JOIN (SELECT t.idproduct, attr FROM (SELECT max(idprodattr)[idprodattr], idproduct, b.idattrset FROM productattr a JOIN product_attr b on a.idattr = b.idattr WHERE idattrset = 160 GROUP BY a.idproduct, b.idattrset )t JOIN productattr a ON t.idprodattr = a.idprodattr JOIN product_attr b ON a.idattr = b.idattr) pa2 ON p.idproduct = pa2.idproduct
LEFT OUTER JOIN (SELECT t.idproduct, attr FROM (SELECT max(idprodattr)[idprodattr], idproduct, b.idattrset FROM productattr a JOIN product_attr b on a.idattr = b.idattr WHERE idattrset = 6 GROUP BY a.idproduct, b.idattrset )t JOIN productattr a ON t.idprodattr = a.idprodattr JOIN product_attr b ON a.idattr = b.idattr) pa3 ON p.idproduct = pa3.idproduct
LEFT OUTER JOIN (SELECT t.idproduct, attr FROM (SELECT max(idprodattr)[idprodattr], idproduct, b.idattrset FROM productattr a JOIN product_attr b on a.idattr = b.idattr WHERE idattrset = 62 GROUP BY a.idproduct, b.idattrset )t JOIN productattr a ON t.idprodattr = a.idprodattr JOIN product_attr b ON a.idattr = b.idattr) pa4 ON p.idproduct = pa4.idproduct
)t
-- END QUERY #1
-- START QUERY #2
DECLARE #listRugSizes TABLE (idmanufacturer int, RugGroup VARCHAR(500), RugSizes VARCHAR(1000))
INSERT INTO #listRugSizes
SELECT
t1.idmanufacturer
, t1.RugGroup
, STUFF(( SELECT ', ' + RugSize FROM #TempProdForSiteGoingTrim t2 WHERE t2.RugGroup = t1.RugGroup and t2.idmanufacturer = t1.idmanufacturer FOR XML PATH(''), TYPE ).value('.', 'varchar(max)'), 1, 1, '') [Values]
FROM
#TempProdForSiteGoingTrim t1
GROUP BY
t1.RugGroup
, t1.idmanufacturer
INSERT INTO [NewTableForSiteGoingTrim]
SELECT
p.idProduct
, p.sku
, p.description
, p.listPrice
, p.price
, p.imageUrl
, p.smallImageUrl
, p.sortOrder
, p.idManufacturer
, p.pgroup
, p.ruggroup
, c.idCategory
, c.idCategory [fidcategory]
, c.idParentCategory
, c.idParentCategory [gidcategory]
, pc.idParentCategory [hidCategory]
, ppc.idParentCategory [iidCategory]
, m.Name
, rp.rewrite_key [rewrite_index]
, rm.rewrite_key [rewrite_key]
, color [Color]
, collection [Collection]
, rugsize [RugSize]
, ruggroup.rugcount
, ruggroup.maxprice
, ruggroup.minprice
, rs.RugSizes
, p.rugshape
FROM
#TempProdForSiteGoingTrim p
LEFT OUTER JOIN (
SELECT
MIN(c.idCategory) [idCategory]
, c.idProduct
FROM
(
SELECT
cp.idProduct
, cp.idCategory
FROM
dbo.categories_products cp
JOIN categories c ON cp.idcategory = c.idCategory
WHERE
c.idSite = 24
) c
GROUP BY
c.idProduct
) cp ON p.idProduct = cp.idProduct
LEFT OUTER JOIN categories c ON cp.idCategory = c.idCategory
LEFT OUTER JOIN categories pc ON c.idParentCategory = pc.idCategory
LEFT OUTER JOIN categories ppc ON pc.idParentCategory = ppc.idCategory
LEFT OUTER JOIN manufacturer m ON p.idManufacturer = m.idManufacturer
LEFT OUTER JOIN (SELECT * FROM rewrite WHERE type = 3) rm ON p.idManufacturer = rm.id
LEFT OUTER JOIN (SELECT * FROM rewrite WHERE type = 1) rp ON p.idProduct = rp.id
LEFT OUTER JOIN #listRugSizes rs ON p.RugGroup = rs.RugGroup and p.idmanufacturer = rs.idmanufacturer
LEFT OUTER JOIN
(
SELECT
p.ruggroup
, p.idmanufacturer
, min(price) [minPrice]
, count(*) [RugCount]
, m.maxprice
FROM
#TempProdForSiteGoingTrim p
LEFT OUTER JOIN
(
SELECT
r.ruggroup
, r.idmanufacturer
, max(price) [maxprice]
FROM
#TempProdForSiteGoingTrim r
WHERE
r.idproduct = (SELECT MAX(idproduct) FROM #TempProdForSiteGoingTrim WHERE ruggroup = r.ruggroup AND price = r.price and idmanufacturer = r.idmanufacturer)
GROUP BY
ruggroup
, idmanufacturer
) m ON p.ruggroup = m.ruggroup and p.idmanufacturer = m.idmanufacturer
GROUP BY
p.ruggroup
, m.maxprice
, p.idmanufacturer
) ruggroup ON p.ruggroup = ruggroup.ruggroup and p.idmanufacturer = ruggroup.idmanufacturer
-- END QUERY #2
Edit
When I change the last join "ruggroup" to only group and join by column "ruggroup" and not "ruggroup" and "idmanufacturer" then it works fine.