I have this basic query, bringing back configuration information. Each MatrixCellID is an individual ticket, and each can have multiple StatisticalGroupCodes and StatisicalGroupDescriptions. Currently each MatrixCellID appears multiple times because of its multiple StatisicalGroupCodes. I would like the Code and Description columns to show all in one column, comma separated.
This is my query:
select
cmc.MatrixSheetId,
CMS.MatrixSheetName,
cmc.MatrixCellId,
CMC.Price,
CMC.PriceListId,
CPL.PriceListName,
CPT.Description as PriceTable,
case when CMC.Code <> '' then cmc.code else 'EMPTY' end AS TicketCode,
case when CMC.Name <> '' then cmc.name else 'EMPTY' END AS TicketName,
case when CMC.Description <> '' then cmc.description else 'EMPTY' END AS TicketDescription,
case when CMC.Description2 <> '' then cmc.description2 else 'EMPTY' end AS AdditionalTicketDescription,
CASE WHEN CMCI.AccountMandatory = 1 THEN 'YES' else 'NO' end AS AccountMandatory,
CASE WHEN CDC.Description IS NULL THEN 'NONE' ELSE CDC.Description END AS AccountCategory,
CDT.DocTemplateName AS PrintTemplate,
CTP.Description as TaxPackage,
CT.TaxName,
CASE when CMC.PriceType = 0 then 'Fixed' else 'Variable' end as PriceType,
CCC.CostCenterDescription,
CCC.CostCenterCode,
CCC.CostCenterAK,
CSG.StatisticalGroupCode,
CSG.StatisticalGroupDescription
from
CNF_MatrixCell CMC
inner join CNF_MatrixSheet CMS on CMC.MatrixSheetId = CMS.MatrixSheetId
inner join CNF_PriceList CPL on CMC.PriceListId = CPL.PriceListId
INNER JOIN CNF_MatrixCellInfo CMCI on CMC.MatrixCellId = CMCI.MatrixCellId
left join CNF_DmgCategory CDC on CMCI.AccountDmgCatId = CDC.DmgCategoryId
left join CNF_DocTemplate CDT on CMC.DocTemplateId = CDT.DocTemplateId
LEFT join CNF_TaxPackage CTP on CMC.TaxPackageId = CTP.TaxPackageId
LEFT join CNF_Tax2Package CT2P on CTP.TaxPackageId = CT2P.TaxPackageId
LEFT JOIN CNF_Tax CT on CT2P.TaxId = CT.TaxId
LEFT JOIN CNF_CostCenter_Validity CCCV on CMC.MatrixCellId = cccv.MatrixCellId
LEFT JOIN CNF_CostCenter CCC on CCCV.CostCenterId = CCC.CostCenterId
inner join CNF_PriceTable CPT on CMC.PriceTableId = CPT.PriceTableId
LEFT JOIN CNF_StatisticalGroupValidity CSGV on CMC.MatrixCellId = CSGV.MatrixCellId
LEFT JOIN CNF_StatisticalGroup CSG on CSGV.StatisticalGroupId = CSG.StatisticalGroupId
WHERE CMC.Enabled = 1
AND CCC.Enabled = 1
AND CPT.Enabled = 1
AND CMS.Enabled = 1
ORDER BY
CMS.MatrixSheetId,
CMC.MatrixCellId,
CMC.Code
I have tried to use Stuff and XML Path, but cannot get it work correctly with my joins.
Thank you in advance.
You can use this.
select
cmc.MatrixSheetId,
CMS.MatrixSheetName,
cmc.MatrixCellId,
CMC.Price,
CMC.PriceListId,
CPL.PriceListName,
CPT.Description as PriceTable,
case when CMC.Code <> '' then cmc.code else 'EMPTY' end AS TicketCode,
case when CMC.Name <> '' then cmc.name else 'EMPTY' END AS TicketName,
case when CMC.Description <> '' then cmc.description else 'EMPTY' END AS TicketDescription,
case when CMC.Description2 <> '' then cmc.description2 else 'EMPTY' end AS AdditionalTicketDescription,
CASE WHEN CMCI.AccountMandatory = 1 THEN 'YES' else 'NO' end AS AccountMandatory,
CASE WHEN CDC.Description IS NULL THEN 'NONE' ELSE CDC.Description END AS AccountCategory,
CDT.DocTemplateName AS PrintTemplate,
CTP.Description as TaxPackage,
CT.TaxName,
CASE when CMC.PriceType = 0 then 'Fixed' else 'Variable' end as PriceType,
CCC.CostCenterDescription,
CCC.CostCenterCode,
CCC.CostCenterAK,
STUFF(StatGrpCode.StatGroupCodes,1,1,'') StatGroupCodes,
STUFF(StatGrpCodeDesc.StatGroupDescription,1,1,'') StatGroupDescription
from
CNF_MatrixCell CMC
inner join CNF_MatrixSheet CMS on CMC.MatrixSheetId = CMS.MatrixSheetId
inner join CNF_PriceList CPL on CMC.PriceListId = CPL.PriceListId
INNER JOIN CNF_MatrixCellInfo CMCI on CMC.MatrixCellId = CMCI.MatrixCellId
left join CNF_DmgCategory CDC on CMCI.AccountDmgCatId = CDC.DmgCategoryId
left join CNF_DocTemplate CDT on CMC.DocTemplateId = CDT.DocTemplateId
LEFT join CNF_TaxPackage CTP on CMC.TaxPackageId = CTP.TaxPackageId
LEFT join CNF_Tax2Package CT2P on CTP.TaxPackageId = CT2P.TaxPackageId
LEFT JOIN CNF_Tax CT on CT2P.TaxId = CT.TaxId
LEFT JOIN CNF_CostCenter_Validity CCCV on CMC.MatrixCellId = cccv.MatrixCellId
LEFT JOIN CNF_CostCenter CCC on CCCV.CostCenterId = CCC.CostCenterId
inner join CNF_PriceTable CPT on CMC.PriceTableId = CPT.PriceTableId
LEFT JOIN CNF_StatisticalGroupValidity CSGV on CMC.MatrixCellId = CSGV.MatrixCellId
OUTER APPLY
( SELECT ', ' + CSG.StatisticalGroupCode
FROM CNF_StatisticalGroup CSG
WHERE CSGV.StatisticalGroupId = CSG.StatisticalGroupId FOR XML PATH('') ) StatGrpCode (StatGroupCodes)
OUTER APPLY
( SELECT ', ' + CSG.StatisticalGroupDescription
FROM CNF_StatisticalGroup CSG
WHERE CSGV.StatisticalGroupId = CSG.StatisticalGroupId FOR XML PATH('') ) StatGrpCodeDesc (StatGroupDescription)
WHERE CMC.Enabled = 1
AND CCC.Enabled = 1
AND CPT.Enabled = 1
AND CMS.Enabled = 1
ORDER BY
CMS.MatrixSheetId,
CMC.MatrixCellId,
CMC.Code
Related
I would like the results to produce a new row in each instance where a condition is met. I'm using a CASE statement but this isn't the way to go since once the first condition is met it stops evaluating the field.
SELECT
Reviews.ReviewID,
CASE
WHEN Score_CorrectID = 0 THEN 'Correct ID Right Party Authentication'
WHEN Score_ProperlyIdentified = 0 THEN 'PCA Properly Identified Itself'
WHEN Score_MiniMiranda = 0 THEN 'Mini-Miranda'
END AS [Error Type]
FROM Reviews INNER JOIN PCAs ON Reviews.PCAID = PCAs.PCAID LEFT JOIN
PCARebuttal ON Reviews.ReviewID = PCARebuttal.ReviewID
WHERE
(Score_CorrectID = 0 OR Score_ProperlyIdentified = 0 OR Score_MiniMiranda =
0)
This produces this:
I would like this:
Use apply:
SELECT r.ReviewID, v.error_type
FROM Reviews r INNER JOIN
PCAs
ON r.PCAID = PCAs.PCAID LEFT JOIN
PCARebuttal pr
ON r.ReviewID = pr.ReviewID OUTER APPLY
(SELECT *
FROM (VALUES (Score_CorrectID, 'Correct ID Right Party Authentication'),
(Score_ProperlyIdentified, 'PCA Properly Identified Itself'),
(Score_MiniMiranda, 'Mini-Miranda')
) v(score, error_type)
WHERE score = 0
) v
WHERE (Score_CorrectID = 0 OR Score_ProperlyIdentified = 0 OR Score_MiniMiranda = 0);
That said, I would probably just concatenate the values into a single column:
SELECT r.ReviewID,
( (CASE WHEN Score_CorrectID = 0 THEN 'Correct ID Right Party Authentication; ' ELSE '' END) +
(CASE WHEN Score_ProperlyIdentified = 0 THEN 'PCA Properly Identified Itself; ' ELSE '' END) +
(CASE WHEN Score_MiniMiranda = 0 THEN 'Mini-Miranda;' ELSE '' END)
) as error_types
FROM Reviews r INNER JOIN
PCAs
ON r.PCAID = PCAs.PCAID LEFT JOIN
PCARebuttal pr
ON r.ReviewID = pr.ReviewID OUTER APPLY
(SELECT *
FROM (VALUES ()
) v(score, error_type)
WHERE score = 0
) v
WHERE (Score_CorrectID = 0 OR Score_ProperlyIdentified = 0 OR Score_MiniMiranda = 0);
Instead of using case, you can use union all instead:
SELECT
Reviews.ReviewID,
'Correct ID Right Party Authentication' AS [Error Type]
FROM Reviews
INNER JOIN PCAs ON Reviews.PCAID = PCAs.PCAID
LEFT JOIN PCARebuttal ON Reviews.ReviewID = PCARebuttal.ReviewID
WHERE Score_CorrectID = 0
UNION ALL
SELECT
Reviews.ReviewID,
'PCA Properly Identified Itself' AS [Error Type]
FROM Reviews
INNER JOIN PCAs ON Reviews.PCAID = PCAs.PCAID
LEFT JOIN PCARebuttal ON Reviews.ReviewID = PCARebuttal.ReviewID
WHERE Score_ProperlyIdentified = 0
UNION ALL
SELECT
Reviews.ReviewID,
'Mini-Miranda' AS [Error Type]
FROM Reviews
INNER JOIN PCAs ON Reviews.PCAID = PCAs.PCAID
LEFT JOIN PCARebuttal ON Reviews.ReviewID = PCARebuttal.ReviewID
WHERE Score_MiniMiranda = 0
I have a view with the below SQL working and pulling data in Oracle SQL developer, but when I import this view in to the OBIEE repository and try to view data I get the error above. Originally the alias was "Segment" but I thought it might have been a Oracle reserved word. I changed it to "Segment_ID" and then to just "SEG" and neither of them have worked.
CREATE OR REPLACE FORCE VIEW "EPM_FCM_STG"."ARM_PROCESS_MONITOR" ("PERIOD", "ACCOUNT_ID", "Company", "Account", "DESCRIPTION", "SRC_SYS_BAL_BUCKET", "BAL_EXP_BUCKET", "SUBSYS_BAL_BUCKET", "ADJ_SUBSYS_BUCKET", "PREPARER_FREQUENCY", "END_DATE_ACTUAL", "PREPARER", "REVIEWER_1", "REVIEWER_2", "NORMAL_BALANCE", "Seg") AS
SELECT R_PeriodEO.PERIOD_NAME AS "PERIOD",
ReconciliationEO.RECONCILIATION_ACCOUNT_ID AS "ACCOUNT_ID",
R_AttributeValueEO1A.VALUE_TEXT AS "Company",
R_AttributeValueEO2A.VALUE_TEXT AS "Account",
ReconciliationEO.RECONCILIATION_DESCRIPTION AS "DESCRIPTION",
R_BalanceSummaryEO3A.AMOUNT AS "SRC_SYS_BAL_BUCKET",
R_TransactionSummaryEO4A.AMOUNT AS "BAL_EXP_BUCKET",
R_BalanceSummaryEO5A.AMOUNT AS "SUBSYS_BAL_BUCKET",
R_TransactionSummaryEO6A.AMOUNT AS "ADJ_SUBSYS_BUCKET",
R_FrequencyEO8A.FREQUENCY_NAME AS "PREPARER_FREQUENCY",
TO_CHAR(ReconciliationEO.ACTUAL_END_DATE, 'YYYY-MM-DD"T"hh:mi:ss') AS "END_DATE_ACTUAL",
(
(SELECT
CASE
WHEN FCM_USERS.FIRST_NAME IS NULL
AND FCM_USERS.LAST_NAME IS NULL
THEN FCM_USERS.USER_LOGIN
ELSE FCM_USERS.FIRST_NAME
|| ' '
|| FCM_USERS.LAST_NAME
END
FROM FCM_USERS
WHERE FCM_USERS.USER_ID = (COALESCE(R_PreparerEO.ACTIVE_USER_ID, R_PreparerEO.USER_ID))
)) AS "PREPARER",
(
(SELECT
CASE
WHEN FCM_USERS.FIRST_NAME IS NULL
AND FCM_USERS.LAST_NAME IS NULL
THEN FCM_USERS.USER_LOGIN
ELSE FCM_USERS.FIRST_NAME
|| ' '
|| FCM_USERS.LAST_NAME
END
FROM FCM_USERS
WHERE FCM_USERS.USER_ID = (COALESCE(R_ReviewerEO1R.ACTIVE_USER_ID, R_ReviewerEO1R.USER_ID))
)) AS "REVIEWER_1",
(
(SELECT
CASE
WHEN FCM_USERS.FIRST_NAME IS NULL
AND FCM_USERS.LAST_NAME IS NULL
THEN FCM_USERS.USER_LOGIN
ELSE FCM_USERS.FIRST_NAME
|| ' '
|| FCM_USERS.LAST_NAME
END
FROM FCM_USERS
WHERE FCM_USERS.USER_ID = (COALESCE(R_ReviewerEO2R.ACTIVE_USER_ID, R_ReviewerEO2R.USER_ID))
)) AS "REVIEWER_2",
CASE ReconciliationEO.NORMAL_BALANCE
WHEN 'C'
THEN 'CREDIT'
ELSE
CASE ReconciliationEO.NORMAL_BALANCE
WHEN 'D'
THEN 'DEBIT'
ELSE
CASE ReconciliationEO.NORMAL_BALANCE
WHEN 'E'
THEN 'EITHER_DEBIT_OR_CREDIT'
ELSE 'N/A'
END
END
END AS "NORMAL_BALANCE",
R_AttributeValueEO15A.VALUE_TEXT AS "Seg"
FROM ARM_RECONCILIATIONS ReconciliationEO
LEFT OUTER JOIN ARM_PERIODS R_PeriodEO
ON (ReconciliationEO.PERIOD_ID = R_PeriodEO.PERIOD_ID)
LEFT OUTER JOIN ARM_ATTRIBUTE_VALUES R_AttributeValueEO1A
ON ReconciliationEO.RECONCILIATION_ID = R_AttributeValueEO1A.OBJECT_ID
AND (R_AttributeValueEO1A.ATTRIBUTE_ID = 100000000027005)
LEFT OUTER JOIN ARM_ATTRIBUTE_VALUES R_AttributeValueEO2A
ON ReconciliationEO.RECONCILIATION_ID = R_AttributeValueEO2A.OBJECT_ID
AND (R_AttributeValueEO2A.ATTRIBUTE_ID = 100000000027021)
LEFT OUTER JOIN ARM_BALANCE_SUMMARIES R_BalanceSummaryEO3A
ON ReconciliationEO.RECONCILIATION_ACCOUNT_ID = R_BalanceSummaryEO3A.PROFILE_ID
AND R_BalanceSummaryEO3A.PERIOD_ID = ReconciliationEO.PERIOD_ID
AND (R_BalanceSummaryEO3A.BUCKET_ID = 100003
AND R_BalanceSummaryEO3A.BALANCE_TYPE = 1
AND 1 = 1)
LEFT OUTER JOIN ARM_TRANSACTION_SUMMARIES R_TransactionSummaryEO4A
ON ReconciliationEO.RECONCILIATION_ID = R_TransactionSummaryEO4A.RECONCILIATION_ID
AND (R_TransactionSummaryEO4A.CURRENCY_BUCKET_ID = 100003
AND R_TransactionSummaryEO4A.TRANSACTION_TYPE = 'BEX'
AND 1 = 1)
LEFT OUTER JOIN ARM_BALANCE_SUMMARIES R_BalanceSummaryEO5A
ON ReconciliationEO.RECONCILIATION_ACCOUNT_ID = R_BalanceSummaryEO5A.PROFILE_ID
AND R_BalanceSummaryEO5A.PERIOD_ID = ReconciliationEO.PERIOD_ID
AND (R_BalanceSummaryEO5A.BUCKET_ID = 100003
AND R_BalanceSummaryEO5A.BALANCE_TYPE = 2
AND 1 = 1)
LEFT OUTER JOIN ARM_TRANSACTION_SUMMARIES R_TransactionSummaryEO6A
ON ReconciliationEO.RECONCILIATION_ID = R_TransactionSummaryEO6A.RECONCILIATION_ID
AND (R_TransactionSummaryEO6A.CURRENCY_BUCKET_ID = 100003
AND R_TransactionSummaryEO6A.TRANSACTION_TYPE = 'SUB'
AND 1 = 1)
LEFT OUTER JOIN ARM_ACCESS R_PreparerEO
ON ReconciliationEO.RECONCILIATION_ID = R_PreparerEO.OBJECT_ID
AND (R_PreparerEO.ACCESS_TYPE = 'P')
LEFT OUTER JOIN ARM_FREQUENCIES R_FrequencyEO8A
ON (R_PreparerEO.FREQUENCY_ID = R_FrequencyEO8A.FREQUENCY_ID)
LEFT OUTER JOIN ARM_ACCESS R_ReviewerEO1R
ON ReconciliationEO.RECONCILIATION_ID = R_ReviewerEO1R.OBJECT_ID
AND (R_ReviewerEO1R.ACCESS_TYPE = 'R'
AND R_ReviewerEO1R.ACCESS_ORDER = 1)
LEFT OUTER JOIN ARM_ACCESS R_ReviewerEO2R
ON ReconciliationEO.RECONCILIATION_ID = R_ReviewerEO2R.OBJECT_ID
AND (R_ReviewerEO2R.ACCESS_TYPE = 'R'
AND R_ReviewerEO2R.ACCESS_ORDER = 2)
LEFT OUTER JOIN ARM_ATTRIBUTE_VALUES R_AttributeValueEO15A
ON ReconciliationEO.RECONCILIATION_ID = R_AttributeValueEO15A.OBJECT_ID
AND (R_AttributeValueEO15A.ATTRIBUTE_ID = 100000000003025)
WHERE ReconciliationEO.PERIOD_ID IS NOT NULL;
The error I get is:
I have following block of code and It takes approx 4-5 minutes to execute. All the tables in this block has large amount of data.
Select
spa.Student_Id,
Cast(Case When ISNULL(#PeriodNumbers, '') = '' Then --PeriodCode Come
CPS.PeriodIdentifier
Else --period number come
Cast(SPA.PeriodNumber as varchar)
End As varchar) As Period,
IsNULL(Count(*), 0) As TotalCount,
AC.ExcessiveAbsAttendanceType,
Cast(SPA.PeriodNumber as varchar) As PeriodNumber
From
(Select Student_ID
From OpenXml(#Handle,'/NewDataSet/Table', 2)
With (Student_ID int) As DT
) FilterDT
Inner Join
dbo.StudentPeriodicAttendanceArchive SPA WITH(NOLOCK) On FilterDT.Student_ID = SPA.Student_ID
Inner Join
dbo.AcademicYear AY WITH(NOLOCK) On AY.AYIdentifier = #AYIdentifier
And AY.School_Domain = #School_Domain
Inner join
dbo.CPsession CPS WITH(NOLOCK) On CPS.SSEC_ID = SPA.SSEC_ID
And CPS.PeriodNumber= spa.periodnumber
And CPS.School_Domain = #School_Domain
And CPS.AYIdentifier = #AYIdentifier
And (CPS.CPSDelStatus = 0 Or CPS.CPSDelStatus Is Null)
Inner Join
dbo.BellTimingScheduleStructure BTSS WITH(NOLOCK) ON BTSS.DayNumber = CPS.WD_ID
And BTSS.SchedulingWeek = CPS.Week
Inner Join
dbo.ClassPeriods CP WITH(NOLOCK) On CP.CP_Id = CPS.CP_ID
And BTSS.CPR_ID = CP.CPR_ID
And BTSS.WeekDay = Case When BTSS.CPRType='D' Then BTSS.WeekDay Else CP.WD_ID End
And BTSS.DayNumber = Case When BTSS.CPRType='D' Then CP.WD_ID Else BTSS.DayNumber End
And BTSS.SchedulingWeek = Case When BTSS.CPRType='W' Then BTSS.SchedulingWeek Else CP.Week End
And BTSS.DateItem = SPA.Attdate
And CP.CPDelStatus = '0'
And IsNull(CP.IsLocked, '0') = '0'
Inner Join
dbo.AttendanceCodes AC WITH(NOLOCK) On AC.AC_ID = SPA.AttCode_ID
Where
SPA.School_Domain = #School_Domain
And AttDate >= Case When #IsYearLongTotals=1 then AY.AYStartDate Else #ActualStartDate End
And AttDate <= Case When #IsYearLongTotals=1 then AY.AYEndDate Else #ActualEndDate End
And IsNull(#Subject_ID, -1) = Case When IsNull(#Subject_ID, -1) <> -1
Then CPS.Subject_ID
Else IsNull(#Subject_ID, -1)
End
Group By
spa.Student_ID,
Cast(Case When ISNULL(#PeriodNumbers, '') = ''
Then CPS.PeriodIdentifier
Else
Cast(SPA.PeriodNumber as varchar)
End As varchar), AC.ExcessiveAbsAttendanceType,
Cast(SPA.PeriodNumber as varchar)
I have a table StudentPeriodicAttendanceArchive which contains attendance information. I want to calculate total present and absent count.
Please suggest what should I do to improve the performance. I am using SQL Server 2008 R2
A bit new to Oracle specific SQL syntax, more familiar with MS SQL Server.
I'm having trouble with a join.
Specifically, the join is supposed to allow me to return the most recent date from a table. (In SQL Server I would just put select top 1 date order by date---with oracle it is confusing!)
Here is my entire query, I'm trying to return the max date for each of the date columns in the select statement with the MAX( prefix. (I know the max prefix isn't the correct syntax to get what I'm after, I'm just listing that here so you know which dates I need max date back on..) How do I get the most current date back for those columns?:
SELECT DISTINCT
req.LCR_REQUEST_ID "Request_ID"
,req.MATTER_ID AS "MatterID_lcr"
,req.CUSTOMER_NAME AS "AccountName_lcr"
,req.STATUS AS "CurrentContractStatus_lcr"
,MAX(HIS.RECORDED_DATE) AS "CurrentStatus_ChangeDate"
--,HIS.STATUS AS "ContractStatus_Historic_lcr"
,MAX(HIS_SUB.RECORDED_DATE) AS "Submitted_Status_Date"
--,HIS_NA.RECORDED_DATE AS "NotAssigned_Status_Date"
,MAX(HIS_AtA.RECORDED_DATE) AS "AssignedToAttorney_Status_Date"
,MAX(HIS_SCIN.RECORDED_DATE) AS "InNegotiation_Status_Date"
,MAX(HIS_EXE.RECORDED_DATE) AS "Executed_Status_Date"
,MAX(HIS_CONV.RECORDED_DATE) AS "ConverteToAmend_Status_Date"
,MAX(HIS_DEAD.RECORDED_DATE) AS "Dead_Status_Date"
,MAX(HIS_COMP.RECORDED_DATE) AS "Completed_Status_Date"
,MAX(HIS_EXP.RECORDED_DATE) AS "Expired_Status_Date"
,CASE
WHEN req.DEALSIZE = 0 THEN ''
WHEN req.DEALSIZE = 1 THEN 'Less Than 100K'
when req.DEALSIZE = 2 THEN '100K-500K'
when req.DEALSIZE = 3 THEN '500K-1M'
when req.DEALSIZE = 4 THEN '1M-10M'
when req.DEALSIZE = 5 THEN '>10M'
END
AS "DealSize_lcr"
,cm_out.PTY_NAME AS "AccountName_cm"
,cm_out.PTY_ID AS "PTYID_CM"
,req.customer_id "PtyID_lcr"
,cm_out.EFFECTIVE_DATE "EffDate_lcr"
,cm_out.INITIALTERM_END_DATE "CPEDate_lcr"
,cm_out.CONTRACT_TERMINATION_DATE "FCTDate_lcr"
,cm_out.TERM_NOTICE_NONCOMP_REASON "ReasonForTermination_lcr"
,cm_out.TERM_TYPE "TermType_lcr"
,cm_out.INITIALTERM_DURATION "InitialTerm_lcr"
,cm_out.INVOICE_TIMEMEAS "InitialTermTymeMeas_lcr"
,cm_out.NUMBER_OF_RENEWALS "NumberOfRenewals_lcr"
,req.AMENDMENT "ParentMatterID_lcr"
,prod.rpg "RPG_lcr"
,prod.SALES_PRODUCT_NAME "Product_lcr"
,prod.CONTRACT_TYPE "ContractType_lcr"
,req.CONTRACT_ROLE "ContractRole_lcr"
,cm_out.METADATA_FLAG "MetaFlag_lcr"
,CASE
WHEN cm_out.DATA_AUTO_IMPORT_YN = 1 THEN 'YES'
WHEN cm_out.REQUESTOR = 'Imported Record' THEN 'YES'
ELSE 'NO'
END
"DataImport_lcr"
,CASE act.actionstatus
WHEN 'Cancel Date Update' THEN 'Yes'
ELSE NULL
END "ActionToCancelAutoDate_lcr"
,req_emp.FIRST_NAME || ' ' || req_emp.LAST_NAME "Requestor_lcr"
,att_emp.FIRST_NAME || ' ' || att_emp.LAST_NAME "Attorney_lcr"
,req.REQUESTOR_DEPARTMENT "Requestor_Department_lcr"
,req.AGREEMENT_TITLE "AgreementTitle_lcr"
,req.DATE_RECORDED
FROM LCR_REQUEST REQ
LEFT JOIN LCR_ACTION ACT ON req.MATTER_ID = act.MATTER_ID
LEFT JOIN CM_CONTRACT_OUTBOUND cm_out ON cm_out.MATTER_ID = NVL(req.MATTER_ID,req.AMENDMENT)
LEFT JOIN LCR_REQUEST_PRODUCT prod_REQ ON prod_req.LCR_REQUEST_ID = req.LCR_REQUEST_ID
LEFT JOIN LCR_PRODUCT PROD ON prod.PRODUCT_ID = prod_req.PRODUCT_ID
LEFT JOIN LCR_EMPLOYEE att_emp ON req.ASSIGNED_TO = att_emp.ORACLE_PERSON_ID
LEFT JOIN LCR_EMPLOYEE req_emp ON req.REQUESTED_BY_ID = req_emp .ORACLE_PERSON_ID
LEFT JOIN LCR_STATUS_HISTORY HIS ON HIS.LCR_REQUEST_ID = req.LCR_REQUEST_ID AND ((HIS.STATUS = REQ.STATUS) OR (HIS.STATUS = 'Assigned to Attorney' AND REQ.STATUS = 'Assigned To Attorney'))
--LEFT JOIN LCR_STATUS_HISTORY HIS_NA ON req.LCR_REQUEST_ID = HIS_NA.LCR_REQUEST_ID AND HIS_NA.STATUS = 'Not Assigned'
LEFT JOIN LCR_STATUS_HISTORY HIS_AtA ON req.LCR_REQUEST_ID = HIS_AtA.LCR_REQUEST_ID AND HIS_AtA.STATUS = 'Assigned to Attorney'
LEFT JOIN LCR_STATUS_HISTORY HIS_SUB ON req.LCR_REQUEST_ID = HIS_SUB.LCR_REQUEST_ID AND HIS_SUB.STATUS = 'Submitted'
LEFT JOIN LCR_STATUS_HISTORY HIS_SCIN ON req.LCR_REQUEST_ID = HIS_SCIN.LCR_REQUEST_ID AND HIS_SCIN.STATUS = 'Submission Complete-In Negotiation'
LEFT JOIN LCR_STATUS_HISTORY HIS_EXE ON req.LCR_REQUEST_ID = HIS_EXE.LCR_REQUEST_ID AND HIS_EXE.STATUS = 'Executed'
LEFT JOIN LCR_STATUS_HISTORY HIS_CONV ON req.LCR_REQUEST_ID = HIS_CONV.LCR_REQUEST_ID AND HIS_CONV.STATUS = 'Converted to amendment.'
LEFT JOIN LCR_STATUS_HISTORY HIS_DEAD ON req.LCR_REQUEST_ID = HIS_DEAD.LCR_REQUEST_ID AND HIS_DEAD.STATUS = 'Dead'
LEFT JOIN LCR_STATUS_HISTORY HIS_COMP ON req.LCR_REQUEST_ID = HIS_COMP.LCR_REQUEST_ID AND HIS_COMP.STATUS = 'Completed'
LEFT JOIN LCR_STATUS_HISTORY HIS_EXP ON req.LCR_REQUEST_ID = HIS_EXP.LCR_REQUEST_ID AND HIS_EXP.STATUS = 'Expired/Terminated'
WHERE REQ.CATEGORY_NAME = 'Sales'
AND
REQ.DATE_RECORDED BETWEEN to_date ('07/01/2012', 'mm/dd/yyyy') AND to_date ('06/30/2013','mm/dd/yyyy')
GROUP BY
req.LCR_REQUEST_ID
,req.MATTER_ID
,req.CUSTOMER_NAME
,req.STATUS
,HIS.RECORDED_DATE
--,HIS.STATUS
,HIS_SUB.RECORDED_DATE
--,HIS_NA.RECORDED_DATE
,HIS_AtA.RECORDED_DATE
,HIS_SCIN.RECORDED_DATE
,HIS_EXE.RECORDED_DATE
,HIS_CONV.RECORDED_DATE
,HIS_DEAD.RECORDED_DATE
,HIS_COMP.RECORDED_DATE
,HIS_EXP.RECORDED_DATE
,CASE
WHEN req.DEALSIZE = 0 THEN ''
WHEN req.DEALSIZE = 1 THEN 'Less Than 100K'
when req.DEALSIZE = 2 THEN '100K-500K'
when req.DEALSIZE = 3 THEN '500K-1M'
when req.DEALSIZE = 4 THEN '1M-10M'
when req.DEALSIZE = 5 THEN '>10M'
END
,cm_out.PTY_NAME
,cm_out.PTY_ID
,req.customer_id
,cm_out.EFFECTIVE_DATE
,cm_out.INITIALTERM_END_DATE
,cm_out.CONTRACT_TERMINATION_DATE
,cm_out.TERM_NOTICE_NONCOMP_REASON
,cm_out.TERM_TYPE
,cm_out.INITIALTERM_DURATION
,cm_out.INVOICE_TIMEMEAS
,cm_out.NUMBER_OF_RENEWALS
,req.AMENDMENT
,prod.rpg
,prod.SALES_PRODUCT_NAME
,prod.CONTRACT_TYPE
,req.CONTRACT_ROLE
,cm_out.METADATA_FLAG
,CASE
WHEN cm_out.DATA_AUTO_IMPORT_YN = 1 THEN 'YES'
WHEN cm_out.REQUESTOR = 'Imported Record' THEN 'YES'
ELSE 'NO'
END
,CASE act.actionstatus
WHEN 'Cancel Date Update' THEN 'Yes'
ELSE NULL
END
,req_emp.FIRST_NAME || ' ' || req_emp.LAST_NAME
,att_emp.FIRST_NAME || ' ' || att_emp.LAST_NAME
,req.REQUESTOR_DEPARTMENT
,req.AGREEMENT_TITLE
,req.DATE_RECORDED;
I wonder how you get multiple columns with a max date using a single TOP 1?
Most of the LEFT JOINs to LCR_STATUS_HISTORY can easily be replaced by a single join using MAX(CASE):
LEFT JOIN
(
SELECT LCR_REQUEST_ID,
MAX(CASE WHEN STATUS = 'Assigned to Attorney' THEN RECORDED_DATE END) AS "AssignedToAttorney_Status_Date"
,MAX(CASE WHEN STATUS = 'Submission Complete-In Negotiation' THEN RECORDED_DATE END) AS "InNegotiation_Status_Date"
,...
FROM LCR_STATUS_HISTORY
GROUP BY LCR_REQUEST_ID
) his
ON HIS.LCR_REQUEST_ID = req.LCR_REQUEST_ID
Then you probably don't need the GROUP BY any more.
And in this join-condition the OR-part can be removed:
((HIS.STATUS = REQ.STATUS) OR (HIS.STATUS = 'Assigned to Attorney' AND REQ.STATUS = 'Assigned To Attorney'))
ON HIS.LCR_REQUEST_ID = req.LCR_REQUEST_ID
I have an "AcctMgr_Flag" that designates a person as the account manager. This is on the table Company_Team. If I send parameter #acctmgr as 'true', I want to return only Activities where #member is the account manager. If #acctmgr is not true, I do not care whether AcctMgr_Flag is true or not.
Every Activity in SO_Activity has an "Assigned_To" column which designates a member_recid. Every Member in Company_Team has an AcctMgr_Flag and Company_RecID. Every Member in v_rpt_Member has a member_recid and a Company_recid.
Here is my code
SELECT v_rpt_Company.Company_Name, SO_Activity.Subject, SO_Activity.Notes,
SO_Activity.Date_Closed, SO_Activity.Last_Update, v_rpt_Member.Member_ID,
v_rpt_ActivityType.SO_Activity_Type_Desc,
v_rpt_ActivityStatus.SO_Act_Status_Desc
FROM v_rpt_Company
LEFT OUTER JOIN SO_Activity
ON v_rpt_Company.Company_RecID = SO_Activity.Company_RecID
LEFT OUTER JOIN v_rpt_Member
ON SO_Activity.Assign_To = v_rpt_Member.Member_ID
LEFT OUTER JOIN Company_Team
ON v_rpt_Member.Member_RecID = Company_Team.Member_RecID AND
v_rpt_Company.Company_RecID = Company_Team.Company_RecID
LEFT OUTER JOIN v_rpt_ActivityType
ON SO_Activity.SO_Activity_Type_RecID=v_rpt_ActivityType.SO_Activity_Type_RecID
LEFT OUTER JOIN v_rpt_ActivityStatus
ON SO_Activity.so_act_status_recid = v_rpt_ActivityStatus.SO_Act_Status_RecID
WHERE (Company_Team.AcctMgr_Flag =
CASE WHEN #acctmgr = 'true' THEN 1 ELSE Company_Team.AcctMgr_Flag END) AND
(SO_Activity.Assign_To = #member) AND
(v_rpt_ActivityStatus.SO_Act_Status_Desc =
CASE WHEN #act_status IS NULL
THEN v_rpt_ActivityStatus.so_act_status_desc ELSE #act_status END) AND
(v_rpt_Company.Company_RecID =
CASE WHEN #company = '' THEN v_rpt_Company.Company_RecID ELSE #company END) AND
(SO_Activity.Last_Update >= CONVERT(datetime, #date_start, 101)) AND
(SO_Activity.Last_Update <= CONVERT(datetime, #date_end, 101))
GROUP BY v_rpt_Company.Company_Name, SO_Activity.Subject, SO_Activity.Notes,
SO_Activity.Date_Closed, SO_Activity.Last_Update, v_rpt_Member.Member_ID,
v_rpt_ActivityType.SO_Activity_Type_Desc,
v_rpt_ActivityStatus.SO_Act_Status_Desc
ORDER BY v_rpt_Company.Company_Name, SO_Activity.Last_Update DESC
Instead of
(Company_Team.AcctMgr_Flag = CASE WHEN #acctmgr = 'true' THEN 1 ELSE Company_Team.AcctMgr_Flag END)
Put this
(#acctmgr != 'true' or Company_Team.AcctMgr_Flag = 1)