I have a query in oracle and i need to add 2 conditions .
I'm new to CTE.Please let me know where i can add the conditions
Query:
WITH cte1 AS
(
SELECT
CASE
WHEN a.firstname IS NOT NULL THEN 1
ELSE 0
END FN
, CASE
WHEN NVL(a.acc_no, b.acc_no) IN (1004, 1003, 1001, 1005, 1007, 1004) THEN 'newacc'
WHEN A.acc_no IN (1003, 1009, 1004) THEN 'newacc'
ELSE 'old ACCOUNT'
END old_or_new
, A.date_created
, A.acc_no
, A.country
, A.organization
FROM
company A
INNER JOIN contacts C
ON C.contactid = A.contact_id
LEFT OUTER JOIN org_contacts d
ON d.contact_id = A.contact_id
FULL OUTER JOIN
(
SELECT
*
FROM
business
WHERE
business_id = 1
AND business_agent = 'N'
) B
ON (
B.auth_id1 = A._auth_id1
AND b.acc_no = a.acc_no
AND b.bus_id = a.bus_id
)
)
SELECT
*
FROM
cte1 x
WHERE
date_created BETWEEN '08/05/2019' AND '12/12/2020'
AND country = 'uk';
2 conditions
where date_created BETWEEN '08/05/2019' and '12/12/2020'
and country='uk'
are not working properly which i have added.
Let me know where i can add this.
NOte: these 2 columns are of table company a
It took me so long to find out the culprit. Instead of A.auth_id1 You used A._auth_id1
Please try below query:
WITH cte1 as
( SELECT
CASE WHEN a.firstname IS NOT NULL THEN 1 ELSE 0 END FN,
CASE
WHEN NVL( a.acc_no, b.acc_no) IN ( 1004,
1003,
1001,
1005,
1007,
1004) THEN
'newacc'
WHEN a.acc_no IN ( 1003,
1009,
1004) THEN
'newacc'
ELSE
'old ACCOUNT'
END old_or_new,
a.date_created ,
a.acc_no,
a.country,
a.organization
FROM company a
INNER JOIN contacts c
ON c.contactid = a.contact_id
and a.date_created BETWEEN '08/05/2019' and '12/12/2020'
and a.country='uk'
LEFT OUTER JOIN org_contacts d
ON d.contact_id = a.contact_id
FULL OUTER JOIN ( SELECT *
FROM business
WHERE business_id = 1
AND business_agent = 'N') b
ON ( b.auth_id1 = a.auth_id1
AND b.acc_no = a.acc_no
AND b.bus_id = a.bus_id))
SELECT *
FROM cte1
Related
I have department mapping table where I have specific status for specific department but different status for all the rest departments that are not in department table.
dep_table:
country
department
status
FIN
D1
C
FIN
D2
C
FIN
**
O
SWE
D1
C
act_table:
country
department
amt
FIN
D1
16
FIN
D3
45
SWE
D1
13
expected result:
country
department
amt
status
FIN
D1
16
C
FIN
D3
45
O
SWE
D1
13
C
I have this but it causes duplicated rows (because joins ** and also non-** rows):
SELECT t1.country, t1.department, t1.amt, t2.status
FROM act_table t1
LEFT OUTER JOIN dep_table t2
ON t1.country = t2.country
AND CASE WHEN t1.department = t2.department THEN 1 WHEN t2.department = '**' THEN 1 END = 1
(This is very simplified scenario - needs to be done in this manner.)
If I understand correctly, you want 'O' if any of the statuses are 'O'. If there are only two statuses, you can use a correlated subquery:
select a.*,
(select d.status
from dep_table d
where d.country = a.country
order by d.status desc
fetch first 1 row only
) as status
from act_table a;
I think two left joins make it more clear :
with
dep_table (country, department, status) as (
values
('FIN', 'D1', 'C'),
('FIN', 'D2', 'C'),
('FIN', '**', 'O'),
('SWE', 'D1', 'C')
),
act_table (country, department, amt) as (
values
('FIN', 'D2', 16),
('FIN', 'D3', 45),
('SWE', 'D1', 13)
)
select
act.country, act.department, act.amt, coalesce(specific.status, rest.status) status
from act_table act
left join dep_table specific using(country, department)
left join dep_table rest on specific.status is null and (rest.country, rest.department) = (act.country, '**')
order by country, department
Use olap function row_number to select first row
select country , department , amt , status
from
(
select a.country , a.department ,
a.amt , d.status ,
row_number() over( partition by a.country , a.department
order by case when d.department = '**' then 1 else 0 end ) as rn1
from dep_table d ,
act_table a
where d.country = a.country
and ( d.department = a.department or d.department = '**' )
) x
where rn1 = 1
I want to select only the first record from each group. So basically I only want the data for first processing date column and don't want the rest of the date for each product.
My current code as below
SELECT
C.AccountID as ABN_ACC ,
C.ProductSymbol,
C.ProductShortName,
S.ReactorProduct AS REC_PROD,
C.CurrencyCode AS PROD_CCY,
C.CountryOfPayment AS PAYCONTRY,
C.DividendValueCur AS PAYCCY,
C.DividendValue AS DIV_AMNT,
CONCAT ((IIF (C.QuantitySettledNoTax_LS = 'S' ,(-1*C.QuantitySettledNoTax),C.QuantitySettledNoTax )),(IIF(C.QuantitySettledTax_LS = 'S',(-1*C.QuantitySettledTax),QuantitySettledTax))) AS DIVQTY ,
C.ExdividendDate AS EXDATE,
C.Recorddate AS RECDATE,
C.DividendPayDate AS PAYDATE
From "LiquidCDW". [Staging].[CA_CorporateActions] AS C
RIGHT JOIN "LiquidCDW".[Staging].[POS_SettledPositions] AS P ON C.Recorddate = P.ProcessingDate AND C.AccountID = p.AccountID AND C.ProductSymbol = P.ProductSymbol AND C.DividendValueCur = P.CurrencyCode
INNER JOIN "LiquidCDW".[Transformation].[Mapping_Product_ABNReactor] AS S ON C.ProductSymbol = S.ReactorProduct AND S.ValidTo IS NULL AND S.ProductType = 'E' AND c.DividendValueCur = S.Currency
where C.ExdividendDate >= '20210201'
ORDER by C.ProductSymbol , C.CurrencyCode
One approach uses ROW_NUMBER:
WITH cte AS (
SELECT
ROW_NUMBER() OVER (PARTITION BY C.ProductSymbol ORDER BY processingDate) rn,
C.AccountID AS ABN_ACC,
C.ProductSymbol,
C.ProductShortName,
S.ReactorProduct AS REC_PROD,
C.CurrencyCode AS PROD_CCY,
C.CountryOfPayment AS PAYCONTRY,
C.DividendValueCur AS PAYCCY,
C.DividendValue AS DIV_AMNT,
CONCAT((IIF(C.QuantitySettledNoTax_LS = 'S',
(-1*C.QuantitySettledNoTax), C.QuantitySettledNoTax)),
(IIF(C.QuantitySettledTax_LS = 'S',
(-1*C.QuantitySettledTax),QuantitySettledTax))) AS DIVQTY,
C.ExdividendDate AS EXDATE,
C.Recorddate AS RECDATE,
C.DividendPayDate AS PAYDATE
FROM [LiquidCDW].[Staging].[CA_CorporateActions] AS C
RIGHT JOIN "LiquidCDW".[Staging].[POS_SettledPositions] AS P
ON C.Recorddate = P.ProcessingDate AND
C.AccountID = p.AccountID AND
C.ProductSymbol = P.ProductSymbol AND
C.DividendValueCur = P.CurrencyCode
INNER JOIN [LiquidCDW].[Transformation].[Mapping_Product_ABNReactor] AS S
ON C.ProductSymbol = S.ReactorProduct AND
S.ValidTo IS NULL AND
S.ProductType = 'E' AND
C.DividendValueCur = S.Currency
WHERE
C.ExdividendDate >= '20210201'
)
SELECT *
FROM cte
WHERE rn = 1
ORDER BY ProductSymbol, CurrencyCode;
I'm looking for general pointers about how to do the following :
I have a chart that looks like this :
The following is my SQL so far , where I am using a WITH clause:
WITH WithSubquery1 AS (
SELECT AUTHORIZATION_STATUS AS "TOTAL AUTHO", COUNT(authorization_status) AS "Requisition Lines Count", LOCATION_CODE AS "Location",
imcb.SEGMENT1 AS "CATEGORY"
FROM
apps.po_requisition_headers_all prha
JOIN apps.po_requisition_lines_all prla ON prla.REQUISITION_HEADER_ID = prha.REQUISITION_HEADER_ID
AND (prha.CANCEL_FLAG = 'N' OR prha.CANCEL_FLAG IS NULL )
JOIN INV.MTL_CATEGORIES_B imcb ON prla.category_id = imcb.category_id
JOIN HR.PER_ALL_PEOPLE_F P ON P.person_id = prha.preparer_id
JOIN apps.HR_LOCATIONS ahl ON prla.deliver_to_location_id = ahl.location_id
JOIN apps.FND_USER afu ON p.person_id = afu.employee_id
WHERE prla.CREATION_DATE >= '13-JUN-14'
AND P.effective_start_date >=
ALL (SELECT p_temp.EFFECTIVE_START_DATE
FROM HR.PER_ALL_PEOPLE_F p_temp
WHERE P.PERSON_ID = p_temp.PERSON_ID)
AND P.current_employee_flag = 'Y'
AND ahl.country IN ( 'US', 'CA', 'MX' ) /* countries in NA */
AND imcb.SEGMENT1 = 'NONBOM'
GROUP BY
imcb.SEGMENT1 , authorization_status, LOCATION_CODE
ORDER BY Location_code Asc
) ,
WithSubquery2 AS
(
SELECT AUTHORIZATION_STATUS AS "APPROVED AUTHO", COUNT(authorization_status) AS "Requisition Lines Apprvd Count", LOCATION_CODE AS "Location",
imcb.SEGMENT1 AS "CATEGORY"
FROM
apps.po_requisition_headers_all prha
JOIN apps.po_requisition_lines_all prla ON prla.REQUISITION_HEADER_ID = prha.REQUISITION_HEADER_ID
AND (prha.CANCEL_FLAG = 'N' OR prha.CANCEL_FLAG IS NULL )
JOIN INV.MTL_CATEGORIES_B imcb ON prla.category_id = imcb.category_id
JOIN HR.PER_ALL_PEOPLE_F P ON P.person_id = prha.preparer_id
JOIN apps.HR_LOCATIONS ahl ON prla.deliver_to_location_id = ahl.location_id
JOIN apps.FND_USER afu ON p.person_id = afu.employee_id
WHERE prla.CREATION_DATE >= '13-JUN-14'
AND P.effective_start_date >=
ALL (SELECT p_temp.EFFECTIVE_START_DATE
FROM HR.PER_ALL_PEOPLE_F p_temp
WHERE P.PERSON_ID = p_temp.PERSON_ID)
AND P.current_employee_flag = 'Y'
and AUTHORIZATION_STATUS = 'APPROVED'
AND ahl.country IN ( 'US', 'CA', 'MX' ) /* countries in NA */
AND imcb.SEGMENT1 = 'NONBOM'
GROUP BY
imcb.SEGMENT1 , authorization_status, LOCATION_CODE
ORDER BY Location_code Asc
)
SELECT WithSubquery1."TOTAL AUTHO", WithSubquery1."Requisition Lines Count", WithSubquery2."APPROVED AUTHO", WithSubquery2."Requisition Lines Apprvd Count"
FROM
WithSubquery1 JOIN WithSubquery2
ON
WithSubquery1."Location" = WithSubquery2."Location"
The problem I'm having is that I'm not sure how to generate SQL so that it has the indentation shown, with the "Ship to" location having spaces underneath it for each of the 5 subcategories ("#Requisition Lines", "#Requisition Lines Approved" etc) . The results I get so far look like this :
This is confusing to read , and doesn't have the hanging -indent.
any tips appreciated, thanks !
Usually, I'd say you should worry about display issues in your front end and not in your SQL. However, you can employ this technique if you want to:
WITH d AS (
SELECT 'Canada' loc, 'APPROVED' status, 5 this_week FROM DUAL UNION ALL
SELECT 'Canada' loc, 'NOT APPROVED' status, 6 this_week FROM DUAL UNION ALL
SELECT 'New York' loc, 'APPROVED' status, 15 this_week FROM DUAL UNION ALL
SELECT 'Philadelphia' loc, 'APPROVED' status, 8 this_week FROM DUAL UNION ALL
SELECT 'Philadelphia' loc, 'NOT APPROVED' status, 2 this_week FROM DUAL )
SELECT case when row_number() over ( partition by loc order by status ) = 1 THEN loc else null end loc_display, status, this_week From d
-- make sure your order by matches your partition and order by
order by loc, status;
I have a SQL query. Below is the query
select
ID,
replace(replace(replace(replace([Name],',',''),'"',''),':',''),'?','') [Name] ,
replace(replace([Description],',',''),'"','') [Description],
[GUID],
Bussinesskey
from course
where COURSESTATUS = 'Published' and RETIREDTF = 0
and
bussinesskey in
(
...
)
and id in (
select c.id from course c
inner join COURSE_CUSTOMERENTITLEMENT cce on cce.COURSE_ID = c.ID
inner join CUSTOMERENTITLEMENT ce on ce.id = cce.CUSTOMERENTITLEMENT_ID
where
ce.ENROLLMENTTYPE = 'Course'
and ce.customer_id = 23753
and c.COURSESTATUS = 'Published' and c.RETIREDTF = 0
UNION
select c.id from course c
inner join COURSE_COURSEGROUP cg on cg.course_id = c.id
inner join COURSEGROUP_CUSTOMERENTITLEMENT cgce on cgce.COURSEGROUP_ID = cg.COURSEGROUP_ID
inner join CUSTOMERENTITLEMENT ce on ce.id = cgce.CUSTOMERENTITLEMENT_ID
where
ce.ENROLLMENTTYPE = 'CourseGroup'
and ce.customer_id = 23753
and c.COURSESTATUS = 'Published' and c.RETIREDTF = 0
)
order by name, id asc
When this query runs then I get the output like the following snapshot
You can see in the screen shot that I am getting 8 names of same type(Contracts). The last id of Contracts is 780697 which is the latest record that is added to database. Now i want that when my query runs then it gets only the latest record. Means instead of showing 8 name of Contarcts. Its only the show the latest one for each course name. Means for Contracts only record with ID 780697 is shown. If other courses has the same result then there latest Id record is shown only. How can I achieve this ?
Thanks
You can try following for achieving latest ID:-
select MAX(ID),
replace(replace(replace(replace([Name],',',''),'"',''),':',''),'?','') [Name] ,
replace(replace([Description],',',''),'"','') [Description],
[GUID],
Bussinesskey
from course
where COURSESTATUS = 'Published' and RETIREDTF = 0
and
bussinesskey in
(
...
)
and id in (
select c.id from course c
inner join COURSE_CUSTOMERENTITLEMENT cce on cce.COURSE_ID = c.ID
inner join CUSTOMERENTITLEMENT ce on ce.id = cce.CUSTOMERENTITLEMENT_ID
where
ce.ENROLLMENTTYPE = 'Course'
and ce.customer_id = 23753
and c.COURSESTATUS = 'Published' and c.RETIREDTF = 0
UNION
select c.id from course c
inner join COURSE_COURSEGROUP cg on cg.course_id = c.id
inner join COURSEGROUP_CUSTOMERENTITLEMENT cgce on cgce.COURSEGROUP_ID = cg.COURSEGROUP_ID
inner join CUSTOMERENTITLEMENT ce on ce.id = cgce.CUSTOMERENTITLEMENT_ID
where
ce.ENROLLMENTTYPE = 'CourseGroup'
and ce.customer_id = 23753
and c.COURSESTATUS = 'Published' and c.RETIREDTF = 0
)
group by [Name], [Description], [GUID], Bussinesskey
order by name, id asc
Here how I did this. I don't know how efficient this is but it's giving me what I am exactly wanting
select ID, [Name], [Description], [GUID], Bussinesskey from (
select row_number() over (partition by [Name] order by id desc) as row, t1.* from (
select
ID,
replace(replace(replace(replace([Name],',',''),'"',''),':',''),'?','') [Name] ,
replace(replace([Description],',',''),'"','') [Description],
[GUID],
Bussinesskey
from course
where COURSESTATUS = 'Published' and RETIREDTF = 0
and bussinesskey in (
'PSTOAS0314001',
...
'RECEAL0510019'
)
and id in (
select c.id from course c
inner join COURSE_CUSTOMERENTITLEMENT cce on cce.COURSE_ID = c.ID
inner join CUSTOMERENTITLEMENT ce on ce.id = cce.CUSTOMERENTITLEMENT_ID
where ce.ENROLLMENTTYPE = 'Course'
and ce.customer_id = 23753
and c.COURSESTATUS = 'Published' and c.RETIREDTF = 0
UNION
select c.id from course c
inner join COURSE_COURSEGROUP cg on cg.course_id = c.id
inner join COURSEGROUP_CUSTOMERENTITLEMENT cgce on cgce.COURSEGROUP_ID = cg.COURSEGROUP_ID
inner join CUSTOMERENTITLEMENT ce on ce.id = cgce.CUSTOMERENTITLEMENT_ID
where ce.ENROLLMENTTYPE = 'CourseGroup'
and ce.customer_id = 23753
and c.COURSESTATUS = 'Published' and c.RETIREDTF = 0
)
)t1
) t
where t.row=1
order by t.name, t.id asc
Thanks
;with Course as
(
Select 50000 ID, 'Contracts' Name, '<BLURB>' [Description], '<GUID>' GUID, 'ARB1' BusinessKey
UNION
Select 60000 ID, 'Contracts' Name, '<BLURB>' [Description], '<GUID>' GUID, 'ARB2' BusinessKey
UNION
Select 70000 ID, 'Contracts' Name, '<BLURB>' [Description], '<GUID>' GUID, 'ARB3' BusinessKey
UNION
Select 80000 ID, 'Contracts' Name, '<BLURB>' [Description], '<GUID>' GUID, 'ARB4' BusinessKey
UNION
Select 90000 ID, 'Contracts' Name, '<BLURB>' [Description], '<GUID>' GUID, 'ARB5' BusinessKey
UNION
Select 40000 ID, 'NOT Contracts' Name, '<BLURB>' [Description], '<GUID>' GUID, 'ARB1' BusinessKey
),
Course_Group AS
(
Select 50000 Course_ID, 1 COURSEGROUP_ID
UNION
Select 60000 Course_ID, 1 COURSEGROUP_ID
UNION
Select 70000 Course_ID, 1 COURSEGROUP_ID
UNION
Select 80000 Course_ID, 1 COURSEGROUP_ID
UNION
Select 90000 Course_ID, 2 COURSEGROUP_ID
UNION
Select 40000 Course_ID, 1 COURSEGROUP_ID
),
CourseGroup_CustomerEntitlement AS
(
Select 1 COURSEGROUP_ID, 1 CUSTOMERENTITLEMENT_ID
--UNION
--Select 2 COURSEGROUP_ID, 2 CUSTOMERENTITLEMENT_ID
--UNION
--Select 2 COURSEGROUP_ID, 4 CUSTOMERENTITLEMENT_ID
),
Course_CustomerEntitlement AS
(
Select 50000 Course_ID, 3 CUSTOMERENTITLEMENT_ID
UNION
Select 60000 Course_ID, 3 CUSTOMERENTITLEMENT_ID
UNION
Select 90000 Course_ID, 3 CUSTOMERENTITLEMENT_ID
UNION
Select 40000 Course_ID, 4 CUSTOMERENTITLEMENT_ID
),
CustomerEntitlement AS
(
Select 1 ID, 23753 Customer_ID, 'CourseGroup' ENROLLMENTTYPE
UNION
Select 2 ID, 7 Customer_ID, 'NOT COURSE GROUP' ENROLLMENTTYPE
UNION
Select 3 ID, 23753 Customer_ID, 'Course' ENROLLMENTTYPE
UNION
Select 4 ID, 7 Customer_ID, 'NOT COURSE' ENROLLMENTTYPE
),
CTE_base_data as (
SELECT
C.ID,
replace(replace(replace(replace(C.[Name],',',''),'"',''),':',''),'?','') [Name] ,
replace(replace(C.[Description],',',''),'"','') [Description],
C.[GUID],
C.Businesskey
FROM Course C
JOIN Course_Group CG ON CG.Course_ID = C.ID
JOIN CourseGroup_CustomerEntitlement CG_CE ON CG_CE.COURSEGROUP_ID = CG.COURSEGROUP_ID
JOIN CustomerEntitlement CE_GROUP ON CE_GROUP.ID = CG_CE.CUSTOMERENTITLEMENT_ID
AND CE_GROUP.ENROLLMENTTYPE = 'CourseGroup'
WHERE
CE_GROUP.Customer_ID = 23753
UNION
SELECT
C.ID,
replace(replace(replace(replace([Name],',',''),'"',''),':',''),'?','') [Name] ,
replace(replace([Description],',',''),'"','') [Description],
[GUID],
Businesskey
FROM Course c
JOIN Course_CustomerEntitlement CCE ON CCE.Course_ID = C.ID
JOIN CustomerEntitlement CE_COURSE ON CE_COURSE.ID = CCE.CUSTOMERENTITLEMENT_ID
AND CE_COURSE.ENROLLMENTTYPE = 'COURSE'
WHERE
CE_COURSE.Customer_ID = 23753
--and COURSESTATUS = 'Published'
--and RETIREDTF = 0
--and businesskey in
-- (
-- ...
-- )
),
CTE_max_data as (
Select name, max(ID) ID
from CTE_base_data
group by name
)
Select Data.*
from CTE_base_data Data
JOIN CTE_max_data Filter
ON Data.ID = Filter.ID
AND Data.Name = Filter.Name
order by name, id asc
This yields:
ID Name Description GUID Businesskey
90000 Contracts ARB5
40000 NOT Contracts ARB1
Please advise where my data assumptions fall flat.
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