Error cannot generate SQL for Custom SQL at BO - sql

I'm using business object 4 and currently developing a report using custom SQL. Total object and data type selected using custom sql and object at webbi already the same. But when I try to validate webbi always sends error cannot generate sql.
How to fix this and what is the cause of this error?
My sql syntax is as follows:
select * from(
SELECT
DISTINCT
CASE WHEN TRIM(msv26A.PROJECT_NO) IS NULL THEN msvPRJ.PROJECT_NO ELSE msv26A.PROJECT_NO END,
msv660.PROJ_DESC,
msv26A.PO_NO,
msv200.SUPPLIER_NAME,
msv26A.SUPPLIER_NO,
msv260.EXT_INV_NO,
msv200.SUP_TYPEX1,
msv260.CURRENCY_TYPE,
msv000_DC0001.DSTRCT_CODE,
msv000_DC0001.DSTRCT_NAME,
msv260.PMT_STATUS,
msv260.DUE_DATE,
msv260.INV_DATE,
msv260.FOR_INV_ORIG,
msv260.LOC_INV_ORIG,
msv260.FOR_INV_AMD,
msv260.LOC_INV_AMD,
msv260.AMT_RETAINED,
msv260.PRESC_PMT_AMT,
msv260.PP_AMT_LOC,
msv260_1.AMT_PAID_FOR,
msv071.REF_CODE,
CASE WHEN EMV260_AGING_RETENTION.LOC_INV_RETENTION IS NULL THEN 0 ELSE EMV260_AGING_RETENTION.LOC_INV_RETENTION END,
CASE WHEN EMV260_AGING_RETENTION.FOR_INV_RETENTION IS NULL THEN 0 ELSE EMV260_AGING_RETENTION.FOR_INV_RETENTION END
FROM
msv200 RIGHT OUTER JOIN msv26A ON (msv26A.SUPPLIER_NO = msv200.SUPPLIER_NO)
INNER JOIN msv000_DC0001 ON (msv000_DC0001.DSTRCT_CODE = msv26A.DSTRCT_CODE)
INNER JOIN msv260 ON (msv26A.DSTRCT_CODE = msv260.DSTRCT_CODE AND msv26A.SUPPLIER_NO = msv260.SUPPLIER_NO AND msv26A.INV_NO = msv260.INV_NO)
LEFT OUTER JOIN msvPRJ ON (msvPRJ.DSTRCT_CODE = msv26A.DSTRCT_CODE AND TRIM(msvPRJ.PO_NO) = trim(msv26A.PO_NO))
LEFT OUTER JOIN msv660 ON (msv26A.DSTRCT_CODE = msv660.DSTRCT_CODE AND (CASE WHEN TRIM(msv26A.PROJECT_NO) IS NULL
THEN msvPRJ.PROJECT_NO ELSE msv26A.PROJECT_NO END) = msv660.PROJECT_NO)
LEFT OUTER JOIN msv260 msv260_1 ON (msv260_1.DSTRCT_CODE = msv260.DSTRCT_CODE and msv260_1.SUPPLIER_NO = msv260.SUPPLIER_NO and msv260_1.INV_NO = msv260.INV_NO)
LEFT OUTER JOIN msv071 ON (msv071.ENTITY_VALUE=msv260.SUPPLIER_NO AND msv071.ENTITY_TYPE='SUP')
LEFT OUTER JOIN (SELECT A.DSTRCT_CODE,
A.SUPPLIER_NO,
A.ORIG_INV_NO,
SUM(CASE WHEN A.LOC_INV_AMD <> 0
THEN A.LOC_INV_AMD ELSE A.LOC_INV_ORIG END) LOC_INV_RETENTION,
SUM(CASE WHEN A.FOR_INV_AMD <> 0
THEN A.FOR_INV_AMD ELSE A.FOR_INV_ORIG END) FOR_INV_RETENTION
FROM msv260 A
WHERE A.FULL_PER_LOADED <= #prompt('Enter Full Period(From):','A','260\Full Per Loaded',Mono,Free,Persistent,,User :3)
AND TRIM(A.PMT_STATUS) >= '30' AND TRIM(A.PMT_STATUS) <= '55'
GROUP BY
A.DSTRCT_CODE,
A.SUPPLIER_NO,
A.ORIG_INV_NO) EMV260_AGING_RETENTION
ON (msv260.DSTRCT_CODE = EMV260_AGING_RETENTION.DSTRCT_CODE
AND msv260.SUPPLIER_NO = EMV260_AGING_RETENTION.SUPPLIER_NO
AND msv260.INV_NO = EMV260_AGING_RETENTION.ORIG_INV_NO)
WHERE
msv26A.DSTRCT_CODE in #prompt('Enter value(s) for Dstrct Code:','A','msv26a\Dstrct Code',Multi,Free,Persistent,,User:5)
AND
TRIM(msv260.PMT_STATUS) >= '30' AND TRIM(msv260.PMT_STATUS) <= '55'
AND
(
( msv260.FULL_PER_LOADED <= #prompt('Enter Full Period(From):','A','260\Full Per Loaded',Mono,Free,Persistent,,User :3)
AND msv260.FULL_PER_PAID = '000000' )
OR
( msv260.FULL_PER_PAID > #prompt('Enter Full Period(To):','A','260\Full Per Paid',Mono,Free,Persistent,,User :4)
AND msv260.FULL_PER_LOADED <= #prompt('Enter Full Period(From):','A','260\Full Per Loaded',Mono,Free,Persistent,,User :3) )
)
AND msv260.CURRENCY_TYPE <> ' '
ORDER BY msv000_DC0001.DSTRCT_CODE, msv260.SUPPLIER_NO, msv200.SUP_TYPEX1, msv260.CURRENCY_TYPE)
WHERE (DSTRCT_CODE,SUPPLIER_NO,EXT_INV_NO) IN (SELECT
DISTINCT DSTRCT_CODE,SUPPLIER_NO,EXT_INV_NO FROM msv900
WHERE DSTRCT_CODE in #prompt('Enter value(s) for Dstrct Code:','A','msv900\Dstrct Code',Multi,Free,Persistent,,User:1)
AND FULL_PERIOD <= #prompt('Enter Full Period(From):','A','msv900\Full Period',Mono,Free,Persistent,,User :2)
AND ACCOUNT_CODE IN ('21101')
)
ORDER BY
PROJECT_NO,
SUPPLIER_NO

Related

Convert multiple rows to columns but as one rows

How do i achieve achieve all this records under one row since every employee has one of each NHIF, NSSF and KRA number?
Below is the query i used but the all appear separate rows.
SELECT DISTINCT
hrmemployeehdr.employeeslno,
hrmemployeehdr.employeecode,
hrmemployeehdr.employeefirstname,
hrmemployeehdr.employeemiddlename,
hrmemployeehdr.employeelastname,
hrmDesignationHdr.DesignationName,
hrmemployeehdr.DateOfBirth,
hrmemployeehdr.DateOfJoin,
hlocationhdr.locationname,
hrmEmployeeIdentityDtl.IDProofReferenceNo AS [National ID],
(CASE
WHEN hrmEmployeeDeductionSettingsDtl.DeductionCode = 1 THEN hrmEmployeeDeductionSettingsDtl.EmployeeRegID
ELSE ''
END) AS NHIF,
(CASE
WHEN hrmEmployeeDeductionSettingsDtl.DeductionCode = 2 THEN hrmEmployeeDeductionSettingsDtl.EmployeeRegID
ELSE ''
END) AS NSSF,
(CASE
WHEN hrmEmployeeDeductionSettingsDtl.DeductionCode = 3 THEN hrmEmployeeDeductionSettingsDtl.EmployeeRegID
ELSE ''
END) AS KRA,
hrmemployeestatusdtl.Email AS [Employee Email],
huser.email AS [User Account Email],
hrmEmployeeGradeHdr.GradeName,
hDepartment.DepartmentName
FROM hrmemployeehdr
JOIN hrmemployeestatusdtl ON hrmemployeestatusdtl.employeeslno = hrmemployeehdr.employeeslno
JOIN hdivision ON hdivision.divisioncode = hrmemployeestatusdtl.divisioncode
JOIN hlocationhdr ON hlocationhdr.locationcode = hrmemployeestatusdtl.workinglocationcode
JOIN hDepartment ON hDepartment.DepartmentCode = hrmemployeestatusdtl.DepartmentCode
JOIN hrmDesignationHdr ON hrmDesignationHdr.DesignationCode = hrmemployeestatusdtl.DesignationCode
JOIN hrmEmployeeCategoryHdr ON hrmEmployeeCategoryHdr.CategoryCode = hrmemployeestatusdtl.CategoryCode
JOIN hrmEmployeeGradeHdr ON hrmEmployeeGradeHdr.GradeCode = hrmemployeestatusdtl.GradeCode
LEFT JOIN huser ON huser.employeeslno = hrmemployeehdr.employeeslno
JOIN hMasterValue ON hMasterValue.MasterValueID = hrmemployeestatusdtl.MasterValue_EmploymentStatusID
JOIN hrmEmployeeIdentityDtl ON hrmEmployeeIdentityDtl.EmployeeSlno = hrmemployeehdr.EmployeeSlno
INNER JOIN hMasterValue a ON a.MasterValueID = hrmEmployeeIdentityDtl.MasterValue_IDProofTypeID
INNER JOIN hrmEmployeeDeductionSettingsDtl ON hrmEmployeeDeductionSettingsDtl.EmployeeSlno = hrmemployeehdr.EmployeeSlno
LEFT JOIN hrmDeductionHdr ON hrmDeductionHdr.DeductionCode = hrmEmployeeDeductionSettingsDtl.DeductionCode
WHERE hrmemployeestatusdtl.employeeslno NOT IN (SELECT hrmemploymentstoppageandtermination.employeeslno
FROM hrmemploymentstoppageandtermination)
AND hrmEmployeeIdentityDtl.MasterValue_IDProofTypeID = 2741005
--and hrmemployeestatusdtl.email = huser.email
--and huser.isemployee = 1
-- select * from huser
ORDER BY employeefirstname ASC;
Use conditional aggregation on the detail table to condense all those rows into one for each employee. Something like:
with edet as (select employeeslno,
max(CASE DeductionCode when 1 THEN EmployeeRegID ELSE '' END) AS NHIF,
max(CASE DeductionCode when 2 THEN EmployeeRegID ELSE '' END) AS NSSF,
max(CASE DeductionCode when 3 THEN EmployeeRegID ELSE '' END) AS KRA
from dbo.hrmEmployeeDeductionSettingsDtl
group by employeeslno)
select emp.employeeslno, ...,
edet.NHIF, edet.NSSF, edet.KRA, ...
from dbo.hrmemployeehdr as emp
inner join edet on emp.employeeslno = edet.employeeslno
...
order by ...
;
Notice the formatting changes that HELP everyone read and understand the code as well as the good habits of using aliases, schema-qualified table names, statement terminator, etc. As already mentioned, the other joins might be contributing to the problem - but this addresses the 1:3 relationship between the header and detail table.

Column 'sip.sip.Application.Id' is invalid in the select list

i have an query that is returning "Column 'sip.sip.Application.Id' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause" error. But i have already included that column in the group by. So i'm not sure why it's still returning this error.
SQL Query
SELECT DISTINCT
a.[ApplicationId]
,a.[Id]
,a.[CompanyId]
,c.name AS CompanyName
,a.[CourseSIPRunId]
,ss.[AdminNo]
,count(CASE ss.StudentStatusCode WHEN 'ASG' THEN 1 ELSE 0 END) NoOfStudentsAllocated
,project.NoOfStudents
,project.[CourseCode]
,a.[AppStatusCode]
,appstat.AppStatusDescription
,project.[ProjectId]
,project.ProjectDescription
,a.CourseSIPRunId
,siprun.[AcadYear] + '-' + siprun.[Batch] As SIPBatch
,c.CompanyUEN
,c.PostalCode AS CompanyPostalCode
,course.CourseName
,project.[ResearchFlag] AS ResearchFlagString
,project.MPFlag AS MPFlagString
,project.[SIPType]
,project.ProjectDescription
,case when project.[SIPType]='OSIP' then 1 else 0 END IsOSIP
,case when project.[ResearchFlag] ='Y' then 1 else 0 END IsResearch
,case when project.[MPFlag] ='Y' then 1 else 0 END IsResearch
,project.MentorProjectLeader
,a.[SpecialRequirement]
,a.[MthlyAllowance]
,a.[OtherAllowance]
,a.[DaysPerWeek]
,a.[WeekdayHoursFrom]
,a.[WeekdayHoursTo]
,a.[SaturdayHoursFrom]
,a.[SaturdayHoursTo]
,a.[SundayHoursFrom]
,a.[SundayHoursTo]
,a.[ShiftWorkRequirement]
,a.[TPContactStaffEmailId]
,a.[SIPConfirmationDate]
,a.[SIPConfirmationBy]
,a.[Remarks]
,a.[SelfSource]
,a.[CreateSource]
,a.[CreatedDate]
,a.[SIPAllocationDate]
,a.[SIPAllocationBy]
,a.[SIPClosureDate]
,a.[SIPClosedBy]
,a.[LastUpdatedBy]
,a.[LastUpdatedDate]
,a.[AppStatusCode]
,a.[StatusReason]
,a.[OSIPCountryCode]
,a.[OSIPState]
,a.[OSIPCity]
,a.[OSIPDetails]
,a.[OverseasAssignment]
,a.[OverseasFrequency]
,a.[OverseasOtherCountry]
,a.[OverseasCountryCode]
,a.[OSIPOtherCountry]
,a.[OthersDetails]
,a.[OthersTPContactName]
,a.[OthersTPDiploma]
,a.[OthersEngagement]
,siprun.[StartDate]
,siprun.[EndDate]
,case when appotherinfo.AppOptionCode is null then 0 else 1 END IsInterviewRequired
,appotherinfo.AppOptionCode
FROM [sip].[sip].[Application] a
LEFT join [sip].[ApplicationStatus] appstat on a.AppStatusCode = appstat.AppStatusCode
LEFT join [sip].[ApplicationProject] project on a.ApplicationId = project.ApplicationId
LEFT JOIN [sip].[ApplicationProjectLO] lo on project.ProjectId = lo.ProjectId
LEFT JOIN [sip].[StudentSIP] ss on ss.ProjectId = lo.ProjectId
LEFT JOIN [sip].[ApplicationProjectSupervisor] s on s.ProjectId = project.ProjectId
LEFT JOIN [sip].[Company] c on c.CompanyId = a.CompanyId
LEFT JOIN [sip].[CourseSIPRun] siprun on a.CourseSIPRunId = siprun.CourseSIPRunId
LEFT JOIN [sip].[V_SIP_COURSE] course on project.CourseCode = course.COURSECODE
LEFT JOIN [sip].[ApplicationOtherInfo] appotherinfo on appotherinfo.ApplicationId = a.ApplicationId
group by a.[ApplicationId]
You include a.[ApplicationId] you don't include a.[Id] The error message is about the 2nd one.

SQL joins returning multiple results

select
tmp.templatedesc Template
,sec.name Section
,q.questiontext Questions,
--,sum(case when q.responserequired = '0' then 1 else null end) as 'N/A'
--,sum(case when q.responserequired = '1' then 1 else null end) as Scored
--,count (case when (qr.weightedscore is not null and tmp.templatedesc = 'QA 30 Day Call Form' and
--sec.name = 'opening' and
--rv.reviewstatusid = 1 )then 1 else null end) as scored
----,(case when qr.weightedscore <> q.weight then rv.reviewid else null end) as fail
--count (case when qr.weightedscore is null then 1 else null end) NA,
--count (case when qr.weightedscore is not null then 1 else null end) scored,
sec.sequencenumber, q.questionnumber, qr.*
from
aqm.dbo.reviewtemplate tmp (nolock)
inner join aqm.dbo.section sec on sec.templateid =tmp.templateid
inner join aqm.dbo.sectionresult scr on scr.sectionid = sec.sectionid
inner join aqm.dbo.questionresult qr on qr.sectionresultid = scr.sectionresultid
inner join aqm.dbo.question q on q.questionid = qr.questionid
--inner join aqm.dbo.questiontype qt on qt.questiontypeid = q.questiontypeid
--left outer join aqm.dbo.questionoption qo on qo.questionid = q.questionid
inner join aqm.dbo.review rv on tmp.templateid = rv.templateid
inner join aqm.dbo.media md on md.mediaid = rv.mediaid
inner join aqm.dbo.iqmuser ut on md.userid = ut.userid
where
rv.reviewstatusid = 1 and
tmp.templatedesc = 'QA 30 Day Call Form'
and sec.name = 'opening' and
convert(varchar,dateadd(hh,-7,rv.reviewdate), 101) = '07/07/2014'
and ut.windowslogonaccount = 'name.name'
and q.questionnumber = 4
--group by
--tmp.templatedesc , sec.name, q.questiontext, sec.sequencenumber, q.questionnumber
order by
sec.sequencenumber, q.questionnumber
the questionresultid and sectionresultid are returning multiple values
how can i fix the joins so that it doesnt return multiple values?
i have it drilled down to a date and a person so that it should only return one row of results( but that obviously didnt work)
not sure what other data i can provide
update
i think it has to do with joins
inner join aqm.dbo.sectionresult scr on scr.sectionid = sec.sectionid
inner join aqm.dbo.questionresult qr on qr.sectionresultid = scr.sectionresultid
as those are the ones returning multiple results.
just dont know how to fix it
First, neither aqm.dbo.questiontype nor aqm.dbo.questionoption are used in your return fields or your where clause so get rid of them if they aren't required.
Second, you are OUTER JOINing on the aqm.dbo.review, but the reviewstatusid and reviewdate are required in the WHERE clause - so this should probably be an INNER JOIN.
Last, best way to debug issues like this is to comment out the COUNT statements and the GROUP BY clause - and see what raw data is being returned.

TOP Returning null

I have the following view below. The second nested select is always returning null when I use the TOP(1) clause, but when I remove this clause it returns the data as expected, just more rows than is needed. Does anyone see anything that would explain this?
SELECT TOP (100) PERCENT
a.ITEMID AS Model
,id.CONFIGID
,id.INVENTSITEID AS SiteId
,id.INVENTSERIALID AS Serial
,it.ITEMNAME AS Description
,CASE WHEN it.DIMGROUPID LIKE '%LR-Y' THEN 'Y'
ELSE 'N'
END AS SerialNumberReqd
,ISNULL(it.PRIMARYVENDORID, N'') AS Vendor
,ISNULL(vt.NAME, N'') AS VendorName
,id.INVENTLOCATIONID AS Warehouse
,id.WMSLOCATIONID AS Bin
,ISNULL(CONVERT(varchar(12), CASE WHEN C.DatePhysical < '1901-01-01'
THEN NULL
ELSE C.DatePhysical
END, 101), N' ') AS DeliveryDate
,CASE WHEN (a.RESERVPHYSICAL > 0
OR C.StatusIssue = 1)
AND c.TransType = 0 THEN C.PONumber
ELSE ''
END AS SoNumber
,'' AS SoDetail
,ISNULL(C.PONumber, N'') AS RefNumber
,ISNULL(CONVERT(varchar(12), CASE WHEN ins.ProdDate < '1901-01-01'
THEN NULL
ELSE ins.PRODDATE
END, 101), N' ') AS DateReceived
,it.STKSTORISGROUPID AS ProdGroup
,ISNULL(CONVERT(varchar(12), CASE WHEN ins.ProdDate < '1901-01-01'
THEN NULL
ELSE ins.PRODDATE
END, 101), N' ') AS ProductionDate
,it.ITEMGROUPID
,it.STKSTORISGROUPID AS MerchandisingGroup
,CASE WHEN a.postedValue = 0
THEN (CASE WHEN D.CostAmtPosted = 0 THEN D.CostAmtPhysical
ELSE D.CostAmtPosted
END)
ELSE a.POSTEDVALUE
END AS Cost
,CASE WHEN a.PHYSICALINVENT = 0 THEN a.Picked
ELSE a.PhysicalInvent
END AS PhysicalOnHand
,ins.STKRUGSQFT AS RugSqFt
,ins.STKRUGVENDSERIAL AS RugVendSerial
,ins.STKRUGVENDDESIGN AS RugVendDesign
,ins.STKRUGEXACTSIZE AS RugExactSize
,ins.STKRUGCOUNTRYOFORIGIN AS RugCountryOfOrigin
,ins.STKRUGQUALITYID AS RugQualityId
,ins.STKRUGCOLORID AS RugColorId
,ins.STKRUGDESIGNID AS RugDesignId
,ins.STKRUGSHAPEID AS RugShapeId
,CASE WHEN (a.AVAILPHYSICAL > 0) THEN 'Available'
WHEN (id.WMSLOCATIONID = 'NIL') THEN 'Nil'
WHEN (a.RESERVPHYSICAL > 0)
AND (c.TransType = 0) THEN 'Committed'
WHEN (a.RESERVPHYSICAL > 0) THEN 'Reserved'
WHEN (id.WMSLOCATIONID LIKE '%-Q') THEN 'Damaged'
WHEN (a.Picked > 0) THEN 'Picked'
ELSE 'UNKNOWN'
END AS Status
,'' AS ReasonCode
,'' AS BaseModel
,ISNULL(CAST(ins.STKSTORISCONFIGINFO AS nvarchar(1000)), N'') AS StorisConfigInfo
,ISNULL(C.ConfigSummary, N'') AS ConfigSummary
FROM
dbo.INVENTSUM AS a WITH (NOLOCK)
INNER JOIN dbo.INVENTDIM AS id WITH (NOLOCK)
ON id.DATAAREAID = a.DATAAREAID
AND id.INVENTDIMID = a.INVENTDIMID
LEFT OUTER JOIN dbo.INVENTTABLE AS it WITH (NOLOCK)
ON it.DATAAREAID = a.DATAAREAID
AND it.ITEMID = a.ITEMID
LEFT OUTER JOIN dbo.VENDTABLE AS vt WITH (NOLOCK)
ON vt.DATAAREAID = it.DATAAREAID
AND vt.ACCOUNTNUM = it.PRIMARYVENDORID
LEFT OUTER JOIN dbo.INVENTSERIAL AS ins WITH (NOLOCK)
ON ins.DATAAREAID = id.DATAAREAID
AND ins.INVENTSERIALID = id.INVENTSERIALID
LEFT OUTER JOIN (SELECT TOP (1)
itt.ITEMID
,invt.INVENTSERIALID
,itt.DATEPHYSICAL AS DatePhysical
,itt.TRANSREFID AS PONumber
,itt.TRANSTYPE AS TransType
,itt.STATUSISSUE AS StatusIssue
,dbo.stkRowsToColumn(itt.INVENTTRANSID, 'STI') AS ConfigSummary
,itt.RECID
FROM
dbo.INVENTTRANS AS itt WITH (NOLOCK)
INNER JOIN dbo.INVENTDIM AS invt WITH (NOLOCK)
ON invt.DATAAREAID = itt.DATAAREAID
AND invt.INVENTDIMID = itt.INVENTDIMID
WHERE
(itt.DATAAREAID = 'STI')
AND (itt.TRANSTYPE IN (0, 2, 3, 8))
AND (invt.INVENTSERIALID <> '')
ORDER BY
itt.RECID DESC) AS C
ON C.ITEMID = a.ITEMID
AND C.INVENTSERIALID = id.INVENTSERIALID
LEFT OUTER JOIN (SELECT TOP (1)
itt2.ITEMID
,invt2.INVENTSERIALID
,itt2.COSTAMOUNTPOSTED AS CostAmtPosted
,itt2.COSTAMOUNTPHYSICAL + itt2.COSTAMOUNTADJUSTMENT AS CostAmtPhysical
,itt2.RECID
FROM
dbo.INVENTTRANS AS itt2 WITH (NOLOCK)
INNER JOIN dbo.INVENTDIM AS invt2 WITH (NOLOCK)
ON invt2.DATAAREAID = itt2.DATAAREAID
AND invt2.INVENTDIMID = itt2.INVENTDIMID
WHERE
(itt2.DATAAREAID = 'STI')
AND (itt2.TRANSTYPE IN (0, 2, 3, 4, 6, 8))
AND (invt2.INVENTSERIALID <> '')
ORDER BY
itt2.RECID DESC) AS D
ON D.ITEMID = a.ITEMID
AND D.INVENTSERIALID = id.INVENTSERIALID
WHERE
(a.DATAAREAID = 'STI')
AND (a.CLOSED = 0)
AND (a.PHYSICALINVENT > 0)
AND (it.ITEMGROUPID LIKE 'FG-%'
OR it.ITEMGROUPID = 'MULTISHIP')
ORDER BY
SiteId
,Warehouse
Presumably, the top value in the subquery doesn't meet the subsequent join conditions. That is, this condition is not met:
D.ITEMID = a.ITEMID AND D.INVENTSERIALID = id.INVENTSERIALID
You are using a left outer join, so NULL values are filled in.
EDIT:
To re-iterate. When you run it with top 1, there are no values (for at least some combinations of the two variables). So, NULL will be filled in for these values. After all, top 1 (with or without the parentheses) returns only one row.
When you run it returning multiple rows, presumably there are matches. For the rows that match, the corresponding values are put it. This is the way that left outer join works.
Gordon's answer is correct as to why I was getting a few rows when removing top and none when I had it. The subquery in question was returning all the rows in the InventTrans table (5 million+) so when I used top, it was just getting the first row which didn't have anything. I realized this was the case when I was trying random high values (e.g 50000) in the TOP clause.
The ultimate fix was to change the left outer joins on the C and D subqueries to Cross Apply, and then change the where clauses to better filter the table (e.g itt.itemid = a.itemid and invt1.inventserialid = id.inventserialid). Using that, I was able to use TOP 1 as expected.

I need help in getting an Oracle SQL Query optimized to run for a longer time period

#DRapp - Revised query below: I need help in optimizing a Oracle/SQL query to run for more than 2 weeks of data. it works for 2 weeks of data then chokes. I inherited this. All the business rules need to stay, but is there a way I can simplify this so it will work for a larger data set? Specific examples and tips would be appreciated. This can be broken down into several queries, but needs to return the same results back. thanks for your help.
Oracle SQL Query code is as follows:
SELECT '1' AS group1,
usr.USR_NAME,
rec.USR_UID_USER,
rec.REC_DATE_PAID,
TO_CHAR(rec.REC_DATE_PAID, 'MM/DD/YYYY (fmDay)') AS group_date,
rec.REC_AMOUNT,
rec.REC_UID,
rec.REG_UID_RECEIPT_GROUP,
rec.REC_TAX1_AMOUNT,
rec.REC_TAX2_AMOUNT,
rec.REC_TAX3_AMOUNT,
rec.REC_AMOUNT - (
CASE
WHEN NVL2(dis.SUMDIS, dis.SUMDIS, 0) <> 0
THEN NVL(Fit2Sum.SumAmt, 0)
ELSE 0
END) - rec.REC_TAX1_AMOUNT - rec.REC_TAX2_AMOUNT - rec.REC_TAX3_AMOUNT
AS "GrossRevAmountnoTax",
rec.REC_AMOUNT,
-(
CASE
WHEN NVL2(dis.SUMDIS, dis.SUMDIS, 0) <> 0
THEN NVL(Fit2Sum.SumAmt, 0)
ELSE 0
END)
AS "GrossRevAmountwTax",
rec.REC_AMOUNT - rec.REC_TAX1_AMOUNT - rec.REC_TAX2_AMOUNT - rec.REC_TAX3_AMOUNT
AS "NetRevenueAmount",
(
CASE
WHEN NVL(FitGrace.GraceAmount, 0) = 0
THEN 1
ELSE 0
END) AS "IsGrace",
(
CASE
WHEN NVL(dis.DIS_UID, 0) = 10
THEN NVL(dis.SUMDIS, 0)
ELSE 0
END) AS "TicoAmount",
(
CASE
WHEN NVL(dis.DIS_UID, 0) = 10
THEN 1
ELSE 0
END) AS "TicoCount",
(
CASE
WHEN NVL(dis.DIS_UID, 0) NOT IN (10, 0)
THEN NVL(dis.SUMDIS, 0)
ELSE 0
END) AS "ValidationAmount",
(
CASE
WHEN NVL(dis.DIS_UID, 0) NOT IN (10, 0)
THEN 1
ELSE 0
END) AS "ValidationCount",
(
CASE
WHEN NVL(PRFGrp.PSMCount, 0) > 1
THEN 'Central Cashier Station'
ELSE TO_CHAR(PRFGrp.MaxFacDescription)
END) AS "FacilityDescription",
(
CASE
WHEN NVL(PRFGrp.PSMCount, 0) > 1
THEN 0
ELSE MAX(PRFGrp.FAC_UID_FACILITY)
END) AS "FacilityUID",
dis.DIS_DESCRIPTION "DiscountDescription",
NVL(dis.countdis, 0) "ValCount",
NVL(dis.SUMDIS, 0) "ValAmount",
NVL(dis.DIS_UID, 0) "DiscountUID",
dis.VLDNUM "ValidationNumber",
dis.THI_NAME "ValidationThirdParty",
dis.VTE_DESCRIPTION "ValidationControlGroup",
pmm.PMM_DESCRIPTION,
pmm.PMM_UID,
pmm.PAY_UID_PAYMENT_TYPE,
psm.PSM_DESCRIPTION,
pol.POL_DESCRIPTION,
cas.CAS_UID,
cas.CAS_OPEN_DATE,
cas.CAS_CLOSE_DATE,
MAX(fit.FIT_SALE_ITEM_DESCRIPTION) AS SaleItem,
NVL(per.PER_NUMBER, rtx.RTX_REPLACEMENT_NUMBER) AS TicketNumber,
rtx.RTX_REPLACEMENT_NUMBER AS ReplacementNumber,
NVL(ptx.PTX_DATE_ENTRY, ptx2.PTX_DATE_ENTRY) AS "EntryTime",
NVL(ptx.PTX_DATE_EXIT, ptx2.PTX_DATE_EXIT) AS "ExitTime",
(TO_CHAR(TRUNC(NVL(ptx.PTX_DATE_EXIT, ptx2.PTX_DATE_EXIT) - NVL(ptx.PTX_DATE_ENTRY,
ptx2.PTX_DATE_ENTRY)))
|| 'd '
|| TO_CHAR(mod(TRUNC((NVL(ptx.PTX_DATE_EXIT, ptx2.PTX_DATE_EXIT) - NVL(ptx.PTX_DATE_ENTRY,
ptx2.PTX_DATE_ENTRY)) * 24), 24))
|| 'h '
|| TO_CHAR(mod(TRUNC((NVL(ptx.PTX_DATE_EXIT, ptx2.PTX_DATE_EXIT) - NVL(ptx.PTX_DATE_ENTRY,
ptx2.PTX_DATE_ENTRY)) * 24 * 60), 60))
|| 'm '
|| TO_CHAR(mod(TRUNC((NVL(ptx.PTX_DATE_EXIT, ptx2.PTX_DATE_EXIT) - NVL(ptx.PTX_DATE_ENTRY,
ptx2.PTX_DATE_ENTRY)) * 24 * 60 * 60), 60))
|| 's') AS "TimeElapsed",
NVL(ptx.LAN_UID_ENTRY, ptx2.LAN_UID_ENTRY) AS "EntryLaneUID",
NVL(ptx.LAN_UID_EXIT, ptx2.LAN_UID_EXIT) AS "ExitLaneUID",
MAX(
(SELECT lan.LAN_DESCRIPTION
FROM lane lan
WHERE lan.LAN_UID = NVL(ptx.LAN_UID_ENTRY, ptx2.LAN_UID_ENTRY)
)) AS "EntryLaneDesc",
MAX(
(SELECT lan.LAN_DESCRIPTION
FROM lane lan
WHERE lan.LAN_UID = NVL(ptx.LAN_UID_EXIT, ptx2.LAN_UID_EXIT)
)) AS "ExitLaneDesc",
crc.CRC_LAST_FOUR,
ctr.CTR_CONFIRMATION_CODE,
ctr.CTR_RETURN_CODE,
ctr.CTR_RETURN_MESSAGE,
ctr.CTR_TRAN_GUID,
ctr.CTR_AUTHORIZATION_REQUEST_DATE,
ctr.CTR_SUCCESS,
ctr.CTR_TRANSACTION_DATE
FROM RECEIPT rec
INNER JOIN USER_ACCOUNT usr
ON rec.USR_UID_USER = usr.USR_UID
INNER JOIN PAYMENT_METHOD_MLKP pmm
ON rec.PMM_UID_PAYMENT_METHOD = pmm.PMM_UID
INNER JOIN financial_transaction fit
ON rec.REC_UID = fit.REC_UID_RECEIPT
LEFT JOIN permission per
ON fit.FIT_SOURCE_OBJ_UID = per.PER_UID
AND fit.TAB_UID_SOURCE_OBJ_TYPE = 10
LEFT JOIN parking_transaction ptx
ON per.PER_UID = ptx.PER_UID_PERMISSION
AND ptx.PTT_UID_TYPE <> 17
LEFT JOIN replacement_transaction rtx
ON fit.FIT_SOURCE_OBJ_UID = rtx.RTX_UID
AND fit.TAB_UID_SOURCE_OBJ_TYPE = 332
LEFT JOIN parking_transaction ptx2
ON rtx.RTX_UID = ptx2.RTX_UID_REPLACEMENT_TRANS
AND ptx.PTT_UID_TYPE <> 17
LEFT JOIN
(SELECT dis.DIS_DESCRIPTION,
dis.DIS_UID,
vte.VTE_DESCRIPTION,
fit2.FIT_UID AS countdis,
fit2.FIT_AMOUNT AS SUMDIS,
vld.VLD_VALIDATION_NUMBER AS VLDNUM,
thi.THI_NAME,
fit2.FIT_UID_PAY_ADJ_REV_ITEM
FROM financial_transaction fit2
INNER JOIN discount_mlkp dis
ON fit2.DIS_UID_DISCOUNT = dis.DIS_UID
LEFT JOIN validation vld
ON fit2.VLD_UID_VALIDATION = vld.VLD_UID
LEFT JOIN enc_print_history esp
ON vld.ESP_UID_PRINT_ID = esp.ESP_UID
LEFT JOIN third_party thi
ON esp.THI_UID_THIRD_PARTY = thi.THI_UID
LEFT JOIN validation_control_group vte
ON vld.VTE_UID_VALIDATION_CTRL_GRP = vte.VTE_UID
WHERE fit2.DIS_UID_DISCOUNT <> 0
) dis ON fit.FIT_UID_PAY_ADJ_REV_ITEM = dis.FIT_UID_PAY_ADJ_REV_ITEM
AND rec.REC_UID =
(SELECT MIN(rec2.REC_UID)
FROM receipt rec2
INNER JOIN receipt_group reg
ON rec2.REG_UID_RECEIPT_GROUP = reg.REG_UID
WHERE rec.REG_UID_RECEIPT_GROUP = reg.REG_UID
)
LEFT JOIN
(SELECT fit2.FIT_UID_PAY_ADJ_REV_ITEM,
SUM(fit2.FIT_AMOUNT) AS SumAmt
FROM financial_transaction fit2
WHERE fit2.DIS_UID_DISCOUNT <> 0
GROUP BY fit2.FIT_UID_PAY_ADJ_REV_ITEM
) Fit2Sum
ON fit.FIT_UID_PAY_ADJ_REV_ITEM = Fit2Sum.FIT_UID_PAY_ADJ_REV_ITEM
LEFT JOIN
(SELECT fit2.FIT_UID,
SUM(fit2.FIT_AMOUNT) AS GraceAmount
FROM financial_transaction fit2
GROUP BY fit2.FIT_UID
) FitGrace
ON fit.FIT_UID_PAY_ADJ_REV_ITEM = FitGrace.FIT_UID
INNER JOIN cashdrawer_session cas
ON rec.CAS_UID_CASHDRAWER_SESSION = cas.CAS_UID
INNER JOIN pos_station psm
ON cas.PSM_UID_STATION = psm.PSM_UID
INNER JOIN pos_station_type_lkp pol
ON psm.POL_UID_STATION_TYPE = pol.POL_UID
LEFT JOIN
(SELECT pfr.PSM_UID_STATION,
COUNT(*) AS PSMCount,
MAX(fac.FAC_DESCRIPTION) AS MaxFacDescription,
pfr.FAC_UID_FACILITY
FROM pos_facility_rel pfr
INNER JOIN facility fac
ON pfr.FAC_UID_FACILITY = fac.FAC_UID
GROUP BY pfr.PSM_UID_STATION,
pfr.FAC_UID_FACILITY
) PRFGrp ON psm.PSM_UID = PRFGrp.PSM_UID_STATION
LEFT JOIN ctr_rec_rel crr
ON rec.REC_UID = crr.REC_UID_RECEIPT
LEFT JOIN credit_card_transaction ctr
ON crr.CTR_UID_CREDIT_CARD_TRANS = ctr.CTR_UID
LEFT JOIN credit_card crc
ON ctr.CRC_UID_PROCESSED = crc.CRC_UID
WHERE pmm.PMM_UID <> 12
GROUP BY usr.USR_NAME,
rec.USR_UID_USER,
rec.REC_DATE_PAID,
TO_CHAR(rec.REC_DATE_PAID, 'MM/DD/YYYY (fmDay)'),
rec.REC_AMOUNT,
rec.REC_UID,
rec.REG_UID_RECEIPT_GROUP,
rec.REC_TAX1_AMOUNT,
rec.REC_TAX2_AMOUNT,
rec.REC_TAX3_AMOUNT,
dis.DIS_DESCRIPTION,
dis.VLDNUM,
dis.THI_NAME,
dis.VTE_DESCRIPTION,
pmm.PMM_DESCRIPTION,
pmm.PMM_UID,
pmm.PAY_UID_PAYMENT_TYPE,
psm.PSM_DESCRIPTION,
pol.POL_DESCRIPTION,
cas.CAS_UID,
cas.CAS_OPEN_DATE,
cas.CAS_CLOSE_DATE,
NVL(per.PER_NUMBER, rtx.RTX_REPLACEMENT_NUMBER),
rtx.RTX_REPLACEMENT_NUMBER,
NVL(ptx.PTX_DATE_ENTRY, ptx2.PTX_DATE_ENTRY),
NVL(ptx.PTX_DATE_EXIT, ptx2.PTX_DATE_EXIT),
NVL(ptx.LAN_UID_ENTRY, ptx2.LAN_UID_ENTRY),
NVL(ptx.LAN_UID_EXIT, ptx2.LAN_UID_EXIT),
crc.CRC_LAST_FOUR,
ctr.CTR_CONFIRMATION_CODE,
ctr.CTR_RETURN_CODE,
ctr.CTR_RETURN_MESSAGE,
ctr.CTR_TRAN_GUID,
ctr.CTR_AUTHORIZATION_REQUEST_DATE,
ctr.CTR_SUCCESS,
ctr.CTR_TRANSACTION_DATE,
fit.FIT_UID_PAY_ADJ_REV_ITEM,
dis.countdis,
dis.SUMDIS,
dis.DIS_UID,
psm.PSM_UID,
(rec.REC_AMOUNT - rec.REC_TAX1_AMOUNT - rec.REC_TAX2_AMOUNT - rec.REC_TAX3_AMOUNT)
If you see a step change in performance (rather than just a linear change in query duration relative to the date range), it's likely to be due to one of three issues:
A change in the query optimisation, which you can check with an execution plan. http://docs.oracle.com/cd/E11882_01/appdev.112/e25788/d_xplan.htm
An increase in the data volume causing a sort operation to switch from optimal to one-pass, or from one-pass to multipass, which you can check by using v$sql_workarea http://docs.oracle.com/cd/E11882_01/server.112/e40402/dynviews_3061.htm#REFRN30256
A change in the "rate" of data -- for example, if you went from 10,000 records per day to 50,000.
These would be the first issues I'd check.
Aside from cleaning (format) of the query to see better what is going on, I made a few small changes. You had a few columns that were based on select count(*) or similar based on whatever the current "fit" record was. From the sounds of your data, that is killing the system some. I've moved those out to three separate LEFT-JOINs to the respective tables (Fit2Sum and FitGrace linked to FIT, and PRFGrp is linked via psm alias).
Now, that said, and I dont know how large volume your tables are, you MAY want to put some limit if there are any date/time fields there that you can restrict (such as only for a month of data...). But, by pre-querying those vs being done on every record COULD be an impact that is killing your process.
SELECT
'1' AS group1,
usr.USR_NAME,
rec.USR_UID_USER,
rec.REC_DATE_PAID,
TO_CHAR(rec.rec_date_paid,'MM/DD/YYYY (fmDay)') AS group_date,
rec.rec_amount,
rec.rec_uid,
rec.reg_uid_receipt_group,
rec.rec_tax1_amount,
rec.rec_tax2_amount,
rec.rec_tax3_amount,
MAX( rec.rec_amount -
- CASE WHEN NVL2( dis.sumdis, dis.sumdis,0) <> 0
THEN NVL( Fit2Sum.SumAmt, 0 )
ELSE 0 END
- rec.rec_tax1_amount
- rec.rec_tax2_amount
- rec.rec_tax3_amount ) AS "GrossRevAmountNoTax",
MAX( rec.rec_amount
- CASE WHEN NVL2(dis.sumdis,dis.sumdis,0) <> 0
THEN NVL( Fit2Sum.SumAmt, 0 )
ELSE 0 END ) AS "GrossRevAmountwTax",
MAX( rec.REC_AMOUNT
- rec.rec_tax1_amount
- rec.rec_tax2_amount
- rec.rec_tax3_amount ) AS "NetRevenueAmount",
MAX( CASE WHEN NVL( FitGrace.GraceAmount, 0 ) = 0
THEN 1
ELSE 0 END) AS "IsGrace",
/*Grace tickets have original fee amount of 0*/
MAX( CASE WHEN NVL(dis.dis_uid,0) = 10
THEN NVL(dis.sumdis,0)
ELSE 0 END ) AS "TicoAmount",
/*dis_uid = 10 is TICO*/
MAX( CASE WHEN NVL(dis.dis_uid,0) = 10
THEN 1
ELSE 0 END ) AS "TicoCount",
MAX( CASE WHEN NVL(dis.dis_uid,0) NOT IN (10,0)
THEN NVL(dis.sumdis,0)
ELSE 0 END ) AS "ValidationAmount",
MAX( CASE WHEN NVL(dis.dis_uid,0) NOT IN (10,0)
THEN 1
ELSE 0 END ) AS "ValidationCount",
MAX( CASE WHEN NVL( PRFGrp.PSMCount, 0 ) > 1
THEN 'Central Cashier Station'
ELSE TO_CHAR(PRFGrp.MaxFacDescription) END ) AS "FacilityDescription",
/*pulls the facility description or Central Cashier Station if a central cashier station*/
MAX( CASE WHEN NVL( PRFGrp.PSMCount, 0 ) > 1
THEN 0
ELSE MAX(PRFGrp.fac_uid_facility) END ) AS "FacilityUID",
dis.dis_description "DiscountDescription",
NVL(dis.countdis,0) "ValCount",
NVL(dis.sumdis,0) "ValAmount",
NVL(dis.dis_uid,0) "DiscountUID",
dis.VLDNUM "ValidationNumber",
dis.thi_name "ValidationThirdParty",
dis.vte_description "ValidationControlGroup",
pmm.PMM_DESCRIPTION,
pmm.pmm_uid,
pmm.pay_uid_payment_type,
psm.psm_description,
pol.pol_description,
cas.cas_uid,
cas.cas_open_date,
cas.cas_close_date,
MAX(fit.fit_sale_item_description) AS SaleItem,
NVL(per.per_number, rtx.rtx_replacement_number) AS TicketNumber,
rtx.rtx_replacement_number AS ReplacementNumber,
NVL(ptx.ptx_date_entry, ptx2.ptx_date_entry) AS "EntryTime",
NVL(ptx.ptx_date_exit, ptx2.ptx_date_exit) AS "ExitTime",
MAX(( TO_CHAR( TRUNC( NVL(ptx.ptx_date_exit, ptx2.ptx_date_exit)
-NVL(ptx.ptx_date_entry, ptx2.ptx_date_entry)))||'d '||
TO_CHAR(mod(TRUNC(( NVL(ptx.ptx_date_exit, ptx2.ptx_date_exit)
-NVL(ptx.ptx_date_entry, ptx2.ptx_date_entry))*24),24))||'h '||
TO_CHAR(mod(TRUNC(( NVL(ptx.ptx_date_exit, ptx2.ptx_date_exit)
-NVL(ptx.ptx_date_entry, ptx2.ptx_date_entry))*24*60),60))||'m '||
TO_CHAR(mod(TRUNC(( NVL(ptx.ptx_date_exit,ptx2.ptx_date_exit)
-NVL(ptx.ptx_date_entry,ptx2.ptx_date_entry))*24*60*60),60))||'s')) AS "TimeElapsed",
/*pulls the time between entry/exit in DD HH MM SS format*/
NVL(ptx.lan_uid_entry, ptx2.lan_uid_entry) AS "EntryLaneUID",
NVL(ptx.lan_uid_exit, ptx2.lan_uid_exit) AS "ExitLaneUID",
MAX( ( SELECT lan.lan_description
FROM lane lan
WHERE lan.lan_uid = NVL(ptx.lan_uid_entry, ptx2.lan_uid_entry))) AS "EntryLaneDesc",
MAX( ( SELECT lan.lan_description
FROM lane lan
WHERE lan.lan_uid = NVL(ptx.lan_uid_exit, ptx2.lan_uid_exit))) AS "ExitLaneDesc",
crc.crc_last_four,
ctr.ctr_confirmation_code,
ctr.ctr_return_code,
ctr.ctr_return_message,
ctr.ctr_tran_guid,
ctr.ctr_authorization_request_date,
ctr.ctr_success,
ctr.ctr_transaction_date
FROM
RECEIPT rec
INNER JOIN USER_ACCOUNT usr
ON rec.USR_UID_USER = usr.USR_UID
INNER JOIN PAYMENT_METHOD_MLKP pmm
ON rec.PMM_UID_PAYMENT_METHOD = pmm.PMM_UID
INNER JOIN financial_transaction fit
ON rec.rec_uid = fit.rec_uid_receipt
LEFT JOIN permission per
ON fit.fit_source_obj_uid = per.per_uid
AND fit.tab_uid_source_obj_type = 10
LEFT JOIN parking_transaction ptx
ON per.per_uid = ptx.per_uid_permission
AND ptx.ptt_uid_type <> 17
LEFT JOIN replacement_transaction rtx
ON fit.fit_source_obj_uid = rtx.rtx_uid
AND fit.tab_uid_source_obj_type = 332
LEFT JOIN parking_transaction ptx2
ON rtx.rtx_uid = ptx2.rtx_uid_replacement_trans
AND ptx.ptt_uid_type <> 17
LEFT JOIN ( SELECT
dis.dis_description,
dis.dis_uid,
vte.vte_description,
fit2.fit_uid AS countdis,
fit2.fit_amount AS SUMDIS,
vld.vld_validation_number AS "VLDNUM",
thi.thi_name,
fit2.fit_uid_pay_adj_rev_item
FROM
financial_transaction fit2
INNER JOIN discount_mlkp dis
ON fit2.dis_uid_discount = dis.dis_uid
LEFT JOIN validation vld
ON fit2.vld_uid_validation = vld.vld_uid
LEFT JOIN enc_print_history esp
ON vld.esp_uid_print_id = esp.esp_uid
LEFT JOIN third_party thi
ON esp.thi_uid_third_party = thi.thi_uid
LEFT JOIN validation_control_group vte
ON vld.vte_uid_validation_ctrl_grp = vte.vte_uid
WHERE
fit2.dis_uid_discount <> 0) dis
ON fit.fit_uid_pay_adj_rev_item = dis.fit_uid_pay_adj_rev_item
AND rec.rec_uid = ( SELECT MIN(rec2.rec_uid)
FROM receipt rec2
INNER JOIN receipt_group reg
ON rec2.reg_uid_receipt_group = reg.reg_uid
WHERE rec.reg_uid_receipt_group = reg.reg_uid)
/*
this is grabbing the detail of any validations used during the transaction. If more then one
validation is used per transient, it will pull the transient permit record multiple times
(equal to the number of validations used). This is by design so we can get the detail info,
must account for these potential duplicates within report using running totals- Added logic to
account for split payments, case statement forces the validation info to only show for the
first receipt of the receipt group- JB21213
*/
LEFT JOIN ( select
fit2.fit_uid_pay_adj_rev_item,
SUM( fit2.fit_amount ) as SumAmt
from
financial_transaction fit2
where
fit2.dis_uid_discount <> 0
group by
fit2.fit_uid_pay_adj_rev_item ) Fit2Sum
ON fit.fit_uid_pay_adj_rev_item = Fit2Sum.fit_uid_pay_adj_rev_item
LEFT JOIN ( SELECT
fit2.fit_uid,
SUM(fit2.fit_amount) as GraceAmount
FROM
financial_transaction fit2
GROUP BY
fit2.fit_uid ) FitGrace
ON fit.fit_uid_pay_adj_rev_item = FitGrace.fit_uid
INNER JOIN cashdrawer_session cas
ON rec.cas_uid_cashdrawer_session = cas.cas_uid
INNER JOIN pos_station psm
ON cas.psm_uid_station = psm.psm_uid
INNER JOIN pos_station_type_lkp pol
ON psm.pol_uid_station_type = pol.pol_uid
LEFT JOIN ( select
prf.psm_uid_station,
COUNT(*) as PSMCount,
MAX(fac.fac_description) as MaxFacDescription
from
pos_facility_rel pfr
INNER JOIN facility fac
ON pfr.fac_uid_facility = fac.fac_uid
group by
prf.psm_uid_station ) PRFGrp
ON psm.psm_uid = PRFGrp.psm_uid_station
LEFT JOIN ctr_rec_rel crr
ON rec.rec_uid = crr.rec_uid_receipt
LEFT JOIN credit_card_transaction ctr
ON crr.ctr_uid_credit_card_trans = ctr.ctr_uid
LEFT JOIN credit_card crc
ON ctr.crc_uid_processed = crc.crc_uid
WHERE
pmm.pmm_uid <> 12
GROUP BY
usr.USR_NAME,
rec.USR_UID_USER,
rec.REC_DATE_PAID,
rec.REC_AMOUNT,
rec.rec_tax1_amount,
rec.rec_tax2_amount,
rec.rec_tax3_amount,
pmm.PMM_DESCRIPTION,
rec.rec_uid,
rec.reg_uid_receipt_group,
psm.psm_description,
cas.cas_uid,
cas.cas_open_date,
cas.cas_close_date,
fit.fit_uid_pay_adj_rev_item,
dis.dis_description,
dis.countdis,
dis.sumdis,
dis.VLDNUM,
dis.dis_uid,
dis.thi_name,
dis.vte_description,
pmm.pay_uid_payment_type,
psm.psm_uid,
pol.pol_description,
pmm.pmm_uid,
TO_CHAR(rec.rec_date_paid,'MM/DD/YYYY (fmDay)'),
NVL(per.per_number,rtx.rtx_replacement_number),
rtx.rtx_replacement_number,
NVL(ptx.ptx_date_entry,ptx2.ptx_date_entry),
NVL(ptx.ptx_date_exit,ptx2.ptx_date_exit),
NVL(ptx.lan_uid_entry,ptx2.lan_uid_entry),
NVL(ptx.lan_uid_exit,ptx2.lan_uid_exit),
crc.crc_last_four,
ctr.ctr_confirmation_code,
ctr.ctr_return_code,
ctr.ctr_return_message,
ctr.ctr_tran_guid,
ctr.ctr_authorization_request_date,
ctr.ctr_success,
ctr.ctr_transaction_date,
(rec.rec_amount
- rec.rec_tax1_amount
- rec.rec_tax2_amount
- rec.rec_tax3_amount );
QUERY CLARIFICATION...
To help understand what is going on with the revised query. On several of the fields, you were running the same query multiple times getting a COUNT(*) based on whatever was the "current" ID, being some facility, person, whatever. If you do that query at the field level, it runs those queries EACH TIME per column, per row...
What I have done was to do a SINGLE pre-aggregation on each respective per facility, person, whatever for those other aliases (such as Fit2Sum, FitGrace, PRFGrp). While keeping the respective "ID" as the group by column in those result sets, the LEFT-JOIN points to one record in each respective set based on that JOIN criteria.
Now, the case/when construct. Since the pre-aggregations have already been performed, and the join is per the respective "ID" column, you no longer need the COUNT() for each column, just grab the final column name from the pre-aggregation query and test that. If the record is found and has a count, do the same as your original COUNT(). In some case, it would return an ID, others, return 0. So, for your example of "GrossRevAmountnoTax",
rec.rec_amount-(CASE WHEN NVL2(dis.sumdis,dis.sumdis,0) <> 0
THEN
(SELECT SUM(fit2.fit_amount)
FROM financial_transaction fit2
WHERE fit.fit_uid_pay_adj_rev_item = fit2.fit_uid_pay_adj_rev_item
AND fit2.dis_uid_discount <> 0)
ELSE 0
END)-rec.rec_tax1_amount-rec.rec_tax2_amount-rec.rec_tax3_amount
AS "GrossRevAmountnoTax",
you are selecting the sum() of the fit_amount based on the fit_uid_pay_adj_rev_item. Since I prequeried this into the Fit2Sum alias, the join is on the fit_uid_pay_adj_rev_item and am just grabbing that column (Fit2Sum.SumAmt) so the query does NOT have to be done repeatedly.
rec.rec_amount -
- CASE WHEN NVL2( dis.sumdis, dis.sumdis,0) <> 0
THEN NVL( Fit2Sum.SumAmt, 0 )
ELSE 0 END
- rec.rec_tax1_amount
- rec.rec_tax2_amount
- rec.rec_tax3_amount AS "GrossRevAmountnoTax",
Again, since it is already sitting at the record in Fit2Sum alias, it can immediately follow with
rec.rec_amount-(CASE WHEN NVL2(dis.sumdis,dis.sumdis,0) <> 0
THEN
(SELECT SUM(fit2.fit_amount)
FROM financial_transaction fit2
WHERE fit.fit_uid_pay_adj_rev_item = fit2.fit_uid_pay_adj_rev_item
AND fit2.dis_uid_discount <> 0)
ELSE 0
END) AS "GrossRevAmountwTax",
without having to requery the set yet again.
So, your issue with the PRFGrp.PSMCount is doing a similar thing. The alias PRFGrp was based on another table, column/condition and summation. The join has that available and SHOULD be visible to your query, not the "fit" alias as I originally had. So, please look at the alias references and final column names in case I missed something and hopefully this clarification makes more sense to you.
ADDITIONAL REVISIONS
The fields that have case/when that are not part of the group by expression are probably causing the failure as you should group by any and all non-aggregate columns in the returned set.
These include GrossRevAmountNoTax, NetRevenueAmount, and others... So, I just changed them to MAX() respectively. Since the group by all those other criteria including the low level ID columns would imply you don't get duplicates, so applying a MAX() to such should be the same value