I'm having trouble calculating the next business day in snowflake SQL, excluding weekends and state based public holidays (not all public holidays are national in Australia).
My end goal is to adjust a service request job open date to align with the clients agreed service hours. so if a job request comes in on a weekend for example, the job is actually logged first thing monday morning contractually. Any idea what I'm missing that's making the non work days calculate incorrectly would be greatly appreciated. Thanks in advance.
This is my code so far for one of the states:
SELECT DISTINCT "Report Date",
CASE WHEN ACT.holiday_name IS NULL AND "Calendar Day in Week" IN ('Sat','Sun') THEN "Calendar Day in Week" ELSE ACT.holiday_name END AS "ACT Public Holiday",
CASE WHEN "ACT Public Holiday" IS NULL THEN 'Work Day' END AS "ACT Work Day",
CASE WHEN "ACT Public Holiday" IS NOT NULL THEN LEAD("Report Date") OVER (PARTITION BY "ACT Work Day" ='Work Day' ORDER BY "Report Date") END AS "ACT Next Work Day"
FROM "ODS"."DWBI_DATAHUB"."V_D_CALENDAR" C
LEFT JOIN "ODS"."ODS"."DS_ALLIANCE_HOLIDAY" ACT ON C."Report Date" = ACT.HOLIDAY_DATE AND (ACT.IS_ALL_NODES = 'Y' OR ACT.NODE_ID = 'ACT')
LEFT JOIN "ODS"."ODS"."DS_ALLIANCE_HOLIDAY" NSW ON C."Report Date" = NSW.HOLIDAY_DATE AND (NSW.IS_ALL_NODES = 'Y' OR NSW.NODE_ID = 'NSW')
LEFT JOIN "ODS"."ODS"."DS_ALLIANCE_HOLIDAY" QLD ON C."Report Date" = QLD.HOLIDAY_DATE AND (QLD.IS_ALL_NODES = 'Y' OR QLD.NODE_ID = 'QLD')
LEFT JOIN "ODS"."ODS"."DS_ALLIANCE_HOLIDAY" VIC ON C."Report Date" = VIC.HOLIDAY_DATE AND (VIC.IS_ALL_NODES = 'Y' OR VIC.NODE_ID = 'VIC')
LEFT JOIN "ODS"."ODS"."DS_ALLIANCE_HOLIDAY" SA ON C."Report Date" = SA.HOLIDAY_DATE AND (SA.IS_ALL_NODES = 'Y' OR SA.NODE_ID = 'SA')
LEFT JOIN "ODS"."ODS"."DS_ALLIANCE_HOLIDAY" WA ON C."Report Date" = WA.HOLIDAY_DATE AND (WA.IS_ALL_NODES = 'Y' OR WA.NODE_ID = 'WA')
LEFT JOIN "ODS"."ODS"."DS_ALLIANCE_HOLIDAY" NT ON C."Report Date" = NT.HOLIDAY_DATE AND (NT.IS_ALL_NODES = 'Y' OR NT.NODE_ID = 'NT')
WHERE "Report Date" IS NOT NULL
ORDER BY "Report Date"
The Results I'm getting from the query above
Related
I am trying to name a column with the first day of the past month so if I am in March the column name should be '2021-01-02' (yyyy-mm-dd), I would prefer that the query wouldn't by dynamic but if there is no other way I will accept such a solution, the column that should show the date is the balance one, see below query:
SELECT
--'Turnover' as "Group Mask"
CASE
WHEN LEFT(t0.FatherNum, 1) = 'R' THEN 'REV'
ELSE 'Other'
END AS "Classification",
t0."AcctName" "Account Name",
SUM(t1.Debit - t1.Credit) * -1 AS Balance
FROM
OACT t0 -- G/L Accounts
INNER JOIN
JDT1 t1 ON T0."AcctCode" = T1."Account"
WHERE
t0."GroupMask" = 4
AND t1.RefDate BETWEEN DATEADD(DAY, 1, EOMONTH(GETDATE(), -2))
AND EOMONTH(GETDATE(), -1)
GROUP BY
t0."AcctCode", t0."AcctName", t1.RefDate, t0.FatherNum
I am working on a project for an organisation which handles tickets. I am doing this with SQL Management Studio. They want to know how much time they spend for each customer per month. What I have at the moment is individual tickets for each customer. Somehow I need to add these values by month an show in seperate column.
The column EndTime has the total time spend for each ticket, now I want to add these values for each month.
SELECT
[dbo].[Company].Name as CompanyName
, convert(time(0), CAST(EndTime AS TIME)) AS 'Worked hours'
,EndTime
,Category.Name as CategoryName
FROM [plugin.tickets].[Ticket]
LEFT JOIN [dbo].Category ON Category.Id = [plugin.tickets].Ticket.CategoryId
LEFT JOIN [plugin.tickets].TicketActivity ON TicketActivity.TicketId = [plugin.tickets].Ticket.Id
LEFT JOIN [dbo].Activity ON Activity.Id = [TicketActivity].ActivityId
LEFT JOIN [dbo].Company ON Company.Id = [plugin.tickets].Ticket.CompanyId
where
[plugin.tickets].[Ticket].status <= 2
AND [plugin.tickets].[Ticket].TypeId = 6 or [plugin.tickets].[Ticket].TypeId = 11
AND [dbo].Category.Name != 'VoIP Telefoni' AND [dbo].Category.Name != 'Beheer'
-- AND [dbo].Activity.EndTime is not null
-- AND DATEDIFF(MINUTE, CAST('00:00:00' AS TIME), CAST(EndTime AS TIME)) > 0
GROUP BY
[dbo].[Company].Name
,EndTime
,EndTime
,Category.Name
ORDER BY
'Worked hours' desc
i have a somewhat complex pair of queries that i am trying to push together functionally.
The first is a (survey query) that is going to pick various demographic and visit information from 6 tables. its centered round a visit id number on the visit table it returns a row for each visit ID and each visits demographic info
the second query (procedure query) joins 5 tables and is also joined to the visit table. it returns a line for each procedure code instead of each visit.
I am trying to array the procedures for each visit into 5 seperate columns and include this into the results for the survey query.
the current procedure query that we use.
Procedure Query
SELECT D
DISTINCT ON ("public".patient_procedure.pproc_visit_num,
"public".procedure_group_cpt_code.pgrpcpt_code)
"public".visit.visit_id AS "Patient ID",
("public".procedure_group_cpt_code.pgrpcpt_code) AS "Procedure Code"
FROM
"public".patient_procedure
LEFT JOIN "public".procedure_desc_master_codes ON "public".patient_procedure.pproc_cpcode = "public".procedure_desc_master_codes.pdescm_id
LEFT JOIN "public".procedure_group_cpt_code ON "public".procedure_desc_master_codes.pdescm_id = "public".procedure_group_cpt_code.pgrpcpt_pdescm_id
LEFT JOIN "public".procedure_group_snomed_codes ON "public".procedure_desc_master_codes.pdescm_id = "public".procedure_group_snomed_codes.pgrpsnomed_pdescm_id
LEFT JOIN "public".visit ON "public".patient_procedure.pproc_visit_num = "public".visit.visit_id
LEFT JOIN "public".physician_table1 ON "public".patient_procedure.pproc_proc_phy1 = "public".physician_table1.phys1_num
ORDER BY
"public".patient_procedure.pproc_visit_num
.
the results look like
Patient id procedure code
-----------|------------------------
1 | A34
1 | B23
1 | C43
2 | F12
3 | A34
3 | E65
4 | T55
4 | U67
.
I have tried using Array_agg on the procedure codes using the following varient
.
SELECT
DISTINCT ON ("public".patient_procedure.pproc_visit_num)
"public".visit.visit_id AS "Patient ID",
array_agg("public".procedure_group_cpt_code.pgrpcpt_code) AS "Procedure Code"
FROM
"public".patient_procedure
LEFT JOIN "public".procedure_desc_master_codes ON "public".patient_procedure.pproc_cpcode = "public".procedure_desc_master_codes.pdescm_id
LEFT JOIN "public".procedure_group_cpt_code ON "public".procedure_desc_master_codes.pdescm_id = "public".procedure_group_cpt_code.pgrpcpt_pdescm_id
LEFT JOIN "public".procedure_group_snomed_codes ON "public".procedure_desc_master_codes.pdescm_id = "public".procedure_group_snomed_codes.pgrpsnomed_pdescm_id
LEFT JOIN "public".visit ON "public".patient_procedure.pproc_visit_num = "public".visit.visit_id
LEFT JOIN "public".physician_table1 ON "public".patient_procedure.pproc_proc_phy1 = "public".physician_table1.phys1_num
group by
"public".visit.visit_id,
"public".patient_procedure.pproc_visit_num,
"public".procedure_group_cpt_code.pgrpcpt_code
ORDER BY
"public".patient_procedure.pproc_visit_num
using the array_agg function the results look like this, duplicating the first value. i presume for each time that patient id occurs in the table/results.
.
.
Patient id procedure code
-----------|------------------------
1 | {A34,A34,A34,A34,A34}
1 | {B23,B23,B23,B23,B23,}
1 | {C43,C43}
2 | {F12,F12}
3 | {A34}
3 | {E65,E65,E65,E65,E65,E65,E65,E65,}
4 | {T55,T55,T55,T55,}
the survey query, i'd like to shove the procedures into the middle
select
distinct on ("public".visit.visit_id)
rpad('1.6.1', 5, '') AS "Survey Designator",
rpad('1.6.1', 5, '') AS "Client ID",
"public".profile.prof_c_ip1lastname AS "Last Name",
left("public".profile.prof_c_ip1midname,1) AS "Middle Initial",
"public".profile.prof_c_ip1firstname AS "First Name",
"public".profile.prof_c_ip1p_addr1 AS "Address 1",
"public".profile.prof_c_ip1p_addr2 AS "Address 2",
"public".profile.prof_c_ip1p_city AS "City",
"public".profile.prof_c_ip1p_state AS "State",
CASE
WHEN "public".profile.prof_c_ip1p_zip = 0 THEN ''
ELSE "public".profile.prof_c_ip1p_zip::text
END AS "ZIP Code",
CASE
WHEN "public".profile.prof_c_arpphone = 0 THEN ''
ELSE "public".profile.prof_c_arpphone::text
END AS "Telephone Number",
CASE WHEN "public".profile.prof_c_ip1p_cell = 0 THEN ''
ELSE "public".profile.prof_c_ip1p_cell::text
END AS "Mobile Number",
rpad('1.6.1', 5, '') AS "MS-DRG",
CASE "public".profile.prof_c_arpsex
when 'M' THEN '1'
WHEN 'F' THEN '2'
ELSE 'M'
END AS "Gender",
to_char("public".visit.visit_date_of_birth, 'MMDDYYYY') AS "Date of Birth",
case LOWER("public".profile.prof_c_ip1language_code)
WHEN 'eng' Then '0'
WHEN 'spa' then '1'
ELSE 'U'
END AS "Preferred Language Code",
"public".visit.visit_mr_num AS "Medical Record Number",
"public".visit.visit_id as "Unique Id",
"public".physician_table1.phys1_npi AS "Attending Physician NPI",
"public".physician_table1.phys1_name AS "Attending Physician Name",
CASE "public".ip_visit_1.ipv1_origin
WHEN '1' THEN '1'
WHEN '2' THEN '2'
WHEN '3' THEN '6'
WHEN '5' THEN '8'
ELSE '9'
END AS "Admission Source",
to_char("public".visit.visit_admit_date, 'MMDDYYYY') AS "Visit or Admit Date",
to_char("public".visit.visit_disch_date, 'MMDDYYYY') AS "Discharge Date",
CASE WHEN "public".ip_visit_1.ipv1_p_email LIKE '%#%'
THEN "public".ip_visit_1.ipv1_p_email ELSE ''
END AS "Email",
CASE "public".visit.visit_admit_phy_key
when '000215' then '1518958503'
when '002515' then '1770546756'
when '003700' then '1255362448'
else ''
end as "Hospitalist 1",
CASE "public".ip_visit_1.ipv1_phy2
when '000215' then '1518958503'
when '002515' then '1770546756'
when '003700' then '1255362448'
else ''
end as "Hospitalist 2",
case "public".er_log.cnerlog_admdt
when '0001-01-01' then 'N'
else 'Y'
end as "ER_ADMIT",
--somehow get procedures in here,
case "public".profile.prof_c_ip1expired_dt
when '0001-01-01' then 'N'
when null then 'N'
else 'Y'
End as "Deceased Flag",
rpad('N', 1, '') AS "State Regulation Flag",
case when "public".visit.visit_date_of_birth > ("public".visit.visit_admit_date - interval '29' day) then 'Y'
else 'N'
end as "Newborn patient",
rpad('$', 1, '') AS "E.O.R Indicator"
FROM
"public".visit
INNER JOIN "public".profile ON "public".profile.prof_c_arpmrnum = "public".visit.visit_mr_num
INNER JOIN "public".physician_table1 ON "public".visit.visit_admit_phy_key = "public".physician_table1.phys1_num
INNER JOIN "public".ip_visit_1 ON "public".ip_visit_1.ipv1_num = "public".visit.visit_id
left JOIN "public".patient_procedure ON "public".visit.visit_id = "public".patient_procedure.pproc_visit_num
left JOIN "public".procedure_desc_master_codes ON "public".patient_procedure.pproc_cpcode = "public".procedure_desc_master_codes.pdescm_id
left JOIN "public".procedure_group_cpt_code ON "public".procedure_desc_master_codes.pdescm_id = "public".procedure_group_cpt_code.pgrpcpt_pdescm_id
left JOIN "public".er_log ON "public".er_log.cnerlog_patnum = "public".visit.visit_id
order BY
"public".visit.visit_id asc
limit 10000
what is a way to have procedures included into the second query? doesn't even have to be fast as the query is going to be run a weekly basis
thanks
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
added edit
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
the below aggregated the row returns on the procedure code . got a lot of duplicates in the aggregated column, but that's still okay. i'll figure that out next
SELECt
"public".visit.visit_id as "visit ID",
string_agg("public".procedure_group_cpt_code.pgrpcpt_code::text, ', ' ) AS "CPT4/HCPCS Code"
FROM
"public".patient_procedure
LEFT JOIN "public".procedure_desc_master_codes ON "public".patient_procedure.pproc_cpcode = "public".procedure_desc_master_codes.pdescm_id
LEFT JOIN "public".procedure_group_cpt_code ON "public".procedure_desc_master_codes.pdescm_id = "public".procedure_group_cpt_code.pgrpcpt_pdescm_id
LEFT JOIN "public".visit ON "public".patient_procedure.pproc_visit_num = "public".visit.visit_id
WHERE
"public".patient_procedure.pproc_date BETWEEN '2017-07-01' AND '2017-07-31' AND
"public".patient_procedure.pproc_visit_num NOT LIKE 'C%'
GROUP BY
"public".visit.visit_id
ORDER BY
"public".visit.visit_id
this works even better, puts column into an array value and removes duplicates with array_agg(distinct "value")
SELECt
"public".visit.visit_id as "visit ID",
array_agg(distinct "public".procedure_group_cpt_code.pgrpcpt_code::text ) AS "CPT4/HCPCS Code"
FROM
"public".patient_procedure
LEFT JOIN "public".procedure_desc_master_codes ON "public".patient_procedure.pproc_cpcode = "public".procedure_desc_master_codes.pdescm_id
LEFT JOIN "public".procedure_group_cpt_code ON "public".procedure_desc_master_codes.pdescm_id = "public".procedure_group_cpt_code.pgrpcpt_pdescm_id
LEFT JOIN "public".visit ON "public".patient_procedure.pproc_visit_num = "public".visit.visit_id
WHERE
"public".patient_procedure.pproc_date BETWEEN '2017-07-01' AND '2017-07-31' AND
"public".patient_procedure.pproc_visit_num NOT LIKE 'C%'
GROUP BY
"public".visit.visit_id
ORDER BY
"public".visit.visit_id
When I see problems like this I tend to think that things are being more complex than they need to be. Chances are if we try to just incorporate the two queries together performance will be poor and maintainability will not be optimal.
When things are not working right with Distinct On and aggregates, chances are you wanted a GROUP BY instead. Note that these do two totally different things but GROUP BY plays much better with aggregates.
In a complex case like this there are some important shortcuts to be aware of:
when you decide what table forms the atomic part of the aggregation, you can group by primary keys of these tables and the tables referencing them outward, saving you the need to group on every column used.
This will also catch certain ambiguities or problems in database design that you may have to handle manually.
Remember also that with PostgreSQL you also have window functions (which are aggregates applied incrementally) and common table expressions which can be helpful in these cases as well.
So my recommendation is to start mapping out the relations on paper, figure out the sort of data you want, determine what table you are using as the base of the aggregation (i.e where one row from that table means one row in your output) and then look at this using group by instead of distinct on.
If this isn't sufficient then having mapped out the data and what you want out, you will be in a better position to ask a question on how to get what you want from SQL.
Can someone help me out with the correct syntax for the below CASE statement please? It's part of a view I am creating where the Return Price is half the cost of the calculated cost in the jobs table when the charge description has "Return" in it. its saying incorrect syntax the the keyword ELSE. Thanks in advance.
`
/****** Object: View [dbo].[MMXREPORT] Script Date: 11/08/2016 14:06:29 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
Alter view [dbo].[MMXREPORT] AS
DECLARE #output int
SELECT isnull(Cus.CUSTOMERNUMBER,'') AS "ACCOUNT",
isnull(dbo.Jobs.DELDATEANDTIME,'') as "DELIVERY DATE" ,
isnull(dbo.Jobs.JOBREFERENCE,'') AS "MMX REFERENCE",
isnull(dbo.Jobs.JOBNUMBER,'') AS "INDIGO REF",
isnull(dbo.Jobs.COLPOSTCODE,'') AS "COLLECTION POSTCODE",
isnull(dbo.Jobs.DELTOWN,'') AS "DELIVERY TOWN",
isnull(dbo.Jobs.DELLPOSTCODE,'') AS "DELIVERY POST CODE",
CASE when (select count (*) from jobcharge jobc inner join charge
on charge.chargeid = jobc.chargeid
where jobc.jobid = jobs.jobid and charge.description like '%return%') > 0 THEN 'YES'
ELSE 'NO' END as "RETURN AUTHORISED",
isnull(dbo.GetClarionTime (DELREADYAT ),'') AS "PLANNED DELIVERY TIME",
'' AS "DRIVER ARRIVAL TIME",
'' AS "ENGINEER ARRIVAL TIME",
isnull(convert(char(5), dbo.Jobs.PODDATEANDTIME, 108),'') AS"POD TIME",
isnull(dbo.Jobs.PODNAME,'') AS"POD NAME",
isnull(dbo.Vehicle.VEHICLE,'') AS "VEHICLE SIZE",
isnull(dbo.Jobs.ACTUALMILEAGE,'0') AS "MILEAGE",
isnull(dbo.Jobs.CALCULATEDCOST,'') AS "MILEAGE PRICE",
SELECT #output = count (*) from jobcharge jobc inner join charge
ON charge.chargeid = jobc.chargeid
WHERE jobc.jobid = jobs.jobid AND charge.description LIKE '%return%'
CASE WHEN #output > 0 THEN SUM(JOBS.CALCULATEDCOST/2)
ELSE '0.00' END
AS "RETURN PRICE",
isnull((select sum (dbo.JobCharge.FLATRATE) from jobcharge inner join charge on charge.chargeid = jobcharge.chargeid
WHERE dbo.Charge.DESCRIPTION like '%congestion%' and jobcharge.jobid = jobs.jobid),0) AS "CONGESTION CHARGE",
'' AS "CONGESTION CHARGE COMMENTS",
isnull((select sum (dbo.JobCharge.FLATRATE) from jobcharge inner join charge on charge.chargeid = jobcharge.chargeid
WHERE dbo.Charge.DESCRIPTION like '%waiting time%' and jobcharge.jobid = jobs.jobid),0) AS "WAITING TIME CHARGE",
'' AS "WAITING TIME COMMENTS",
isnull((select sum (dbo.JobCharge.FLATRATE) from jobcharge inner join charge on charge.chargeid = jobcharge.chargeid
WHERE dbo.Charge.DESCRIPTION like '%hrs%' and jobcharge.jobid = jobs.jobid),0) AS "ANY OTHER CHARGES",
'' AS "ANY OTHER COMMENTS",
'' AS "TOTAL COST",JOBS.CUSTOMERID
FROM dbo.Jobs left outer JOIN
dbo.Vehicle ON dbo.Jobs.VEHICLEID = dbo.Vehicle.VEHICLEID left outer JOIN
-- dbo.JobCharge ON dbo.Jobs.JobID = dbo.JobCharge.JOBID left outer JOIN
dbo.Customer CUS ON dbo.Jobs.CUSTOMERID = CUS.CUSTOMERID
`
Above is the full query.
This should work:
DECLARE #output int
select #output= count (*) from jobcharge jobc inner join charge
on charge.chargeid = jobc.chargeid
where jobc.jobid = jobs.jobid and charge.description like '%return%'
CASE WHEN #output > 0 THEN SUM(JOBS.CALCULATEDCOST/2)
ELSE '0.00' END as "RETURN PRICE",
It seems incomplete query.
So i have assumed that there must be a table named "JOBS".
For that pl try following.
SELECT
CASE WHEN (SELECT COUNT (*)FROM JOBCHARGE JOBC
INNER JOIN CHARGE ON CHARGE.CHARGEID = JOBC.CHARGEID
WHERE JOBC.JOBID = JOBS.JOBID
AND CHARGE.DESCRIPTION LIKE '%return%') > 0
THEN
SUM(JOBS.CALCULATEDCOST/2)
ELSE '0.00'
END as "RETURN PRICE" FROM JOBS
I think you do not need the sum of several rows, but only one value ...
CASE WHEN EXISTS(
select 1 from jobcharge jobc inner join charge
ON charge.chargeid = jobc.chargeid
WHERE jobc.jobid = jobs.jobid AND charge.description LIKE '%return%
) THEN jobs.CALCULATEDCOST/2 ELSE 0.00 END as "RETURN PRICE",
Use exists (select 1 ...) may by faster than select count() ...
I am trying yo classify customers in three groups REMIC, REMIR and HC
Customers with number '682010','682020','683220' are HC --> else are REMIC or REMIR
REMIR = Has no Exposure at Default in Commercial Real Estate (04), but has exposure at default in residential (05)
I have created a case formula, however it keeps giving me the error 3625 - i know I should have counted right, so cannot see the error
select
CU.CD03001 as "Local Customer ID",
case
when "Commercial Real Estate EAD" is null then 'O'
else 'X'
end as "Commercial Status",
case
when "Residential Real Estate EAD" is null then 'O'
else 'X'
end as "Residential Status",
case
when CU.CD03008='DK'
and CU.CD03025 not in ('682010','682020','683220')
and "Commercial Status" = 'O'
and "Residential Status" = 'X'
then 'REMIR'
when CU.CD03008='DK'
and CU.CD03025 in ('682010','682020','683220')
then 'HC'
else 'REMIC'
end as "Customer Group",
CU.CD03010 as Business_Partner_Name,
ORG1.CD01007_Cd as BA1,
ORG1.CD01008 as BA2,
BA2_NM.Acctng_unit_com_nm AS "Banking Unit",
case ORG1.CD01008
when '6002092' then ORG1.region_cd
else ORG1.CD01009
end as BA3,
BA3_NM.Acctng_unit_com_nm AS "Branch Region",
SD.Common_Cust_Seg_Lvl3_CD,
SD.Common_Cust_Seg_Lvl3_Desc,
CU.CD09075 as Rating,
COALESCE(sum(Case when CR.CD09076_Collateral_Category_Cd = '04' then CR.CD09014_Exposure_at_Default else 0 END),0) as "Commercial Real Estate EAD",
COALESCE(sum(Case when CR.CD09076_Collateral_Category_Cd = '05' then CR.CD09014_Exposure_at_Default else 0 END),0) as "Residential Real Estate EAD"
FROM PROD_INT_SL_DX_VIEWS.organization_dim ORG1
LEFT JOIN ( SELECT
Customer_Id,
CD03001,
CD03008,
CD03010,
CD03025,
CD03026,
CD03029,
CD09075
FROM PROD_INT_SL_DX_VIEWS.customer_dim
where CD03025='L'
and CD03008 = 'DK'
group by 1,2,3,4,5,6,7,8 ) CU
ON ORG1.CD01001=CU.CD03026
LEFT JOIN
(SELECT DISTINCT CD01001, Acctng_unit_com_nm
FROM PROD_INT_SL_DX_VIEWS.ORGANIZATION_HIER) AS BA2_NM
ON TRIM(ORG1.CD01008) = TRIM(BA2_NM.CD01001)
LEFT JOIN
(SELECT DISTINCT CD01001, Acctng_unit_com_nm
FROM PROD_INT_SL_DX_VIEWS.ORGANIZATION_HIER) AS BA3_NM
ON TRIM(BA3) = TRIM(BA3_NM.CD01001)
LEFT JOIN PROD_INT_SL_DX_VIEWS.customer_segment_dim SD
ON CU.CD03029=SD.CD03029
LEFT JOIN PROD_INT_SL_CPS_VIEWS.Financial_Fact FF
on CU.Customer_Id=FF.Customer_Id
LEFT JOIN PROD_INT_SL_CPS_VIEWS.PRODUCT_DIM PD
ON FF.Product_Party_Type_Id=PD.Product_Party_Type_Id
LEFT JOIN PROD_INT_SL_CPS_VIEWS.CREDIT_RISK_FACT CR
ON FF.Agreement_Id=CR.Agreement_Id
where BA1='6002000'
and BA2 in ('6002091')
and SD.Common_Cust_Seg_Lvl3_CD in ('C30100','C20100','C10100','RB_C50100','C60100')
and FF.Year_Month_Id in ('201409') and FF.period_type in ('AVGP','AVGY')
and FF.CD12001_Currency_Unit='EUR'
and PD.Language_Code='eng'
group by 1,2,3,4,5,6,7,8,9,10,11,12,13
order by 1