Using select in select in oracle report query - oracle

I am creating a new report where I have only one cursor in the report and the report has no paper layout (it goes directly to a CSV format).
I have a query where I need to make a sub query something like
SELECT
grou.GROUP_ID GROUP_ID
,grou.group_name group_name
....
(((SELECT SUM(nett_instalment_invoice_amount)
FROM instalments
WHERE member_product_id = member_product_id)) subscription)
FROM
....
and so on....
While compiling report I encounter an error saying
Encountered Symbol SELECT while expecting one of the following symbols:
( + -
can this be helped without adding a group by clause at the end?
As I tried an alternative approach by putting in a group by clause and directly using sum function instead of select (sum()).
Please urgent help needed.
Thanks.

there is a simple workaround for this by creating a function let's call it get_installment_inv_sum with one parameter member_product_id like this:
create or replace function get_installment_inv_sum (p_member_product_id number) return number
as
v_sum number
begin
SELECT SUM(nett_instalment_invoice_amount)
into v_sum
FROM instalments
WHERE member_product_id = p_member_product_id;
return v_sum;
end;
then you can call your select like:
SELECT
grou.GROUP_ID GROUP_ID
,grou.group_name group_name
....
,
get_installment_inv_sum(member_product_id) subscription
FROM ...

This is certainly allowed:
select d.dname, (sum(e.sal) from emp e where e.deptno = d.deptno) as dept_sal
from dept d;
And so is this:
select d.dname, sum(e.sal)
from dept d
left outer join emp e on e.deptno = d.deptno
group by d.dname;
So what did you do exactly?

SELECT /*+ ORDERED PUSH_SUBQ*/
11
,'SQ'
,grou.GROUP_ID GROUP_ID
,grou.group_name group_name
,intm.intermediary_id intermediary_id --R3352 AUS Regulatory added new field
,intm.intermediary_name intermediary_name
,regi.registration_id registration_id
,mere.member_id member_id
,memb.title_code title_code
,memb.given_name||' '||memb.family_name member_name
--,mech.birth_date birth_date
,mere.company_employee_ref company_employee_ref
,memb.orig_risk_start_date orig_risk_start_date
,mere.original_bi_joining_date orig_joining_date
,mepr.member_product_id member_product_id
,mepr.member_product_risk_start_date mp_risk_start_date
,mepr.product_id product_id
,INITCAP(prod.product_name) product_name
,cont.currency_code
,mere.customer_status_code
/* ,((SELECT SUM(inst.nett_instalment_invoice_amount)
FROM instalments inst
WHERE inst.member_product_id = mepr.member_product_id)) subscription */
,SUM(inst.nett_instalment_invoice_amount) subscription
FROM registrations regi
,member_registrations mere
,member_products mepr
,contracts cont
,products prod
,members memb
,groups grou
,intermediaries intm
,insurers insu
,instalments inst
WHERE insu.insurer_id = i_insurerid
AND NVL(i_reportdate ,Sysdate) >= cont.contract_risk_start_date
AND NVL(i_reportdate ,Sysdate) < cont.renewal_date
--AND regi.GROUP_ID IN (77648,77658) --Arv
AND prod.insurer_id = insu.insurer_id(+)
AND mere.member_id = memb.member_id
AND mere.member_id = mepr.member_id
AND mepr.contract_pk = cont.contract_pk
AND mepr.product_id = prod.product_id(+)
AND mepr.intermediary_id = intm.intermediary_id(+)
AND mere.registration_id = regi.registration_id
AND mere.registration_id = mepr.registration_id
AND regi.GROUP_ID = grou.group_id
AND inst.member_product_id = mepr.member_product_id
AND grou.group_level_code IN ('G','R')
AND mere.customer_status_code IN ('A','L')
AND family_name_uppercase <> UPPER('zz** Please Ignore This Member **zz')
AND given_name_uppercase <> UPPER('zz** Please Ignore **zz') --l_given_name_uppercase
AND NOT EXISTS
( SELECT 'X'
FROM customer_lapses
WHERE GROUP_ID = regi.GROUP_ID
AND suspend_lapse_ind = 'L'
AND reinstatement_ind = 'N'
AND lapse_effective_date <= NVL(i_reportdate ,Sysdate)
UNION
SELECT 'X'
FROM customer_lapses
WHERE registration_id = regi.registration_id
AND suspend_lapse_ind = 'L'
AND reinstatement_ind = 'N'
AND lapse_effective_date <= NVL(i_reportdate ,Sysdate)
)
AND NOT EXISTS
( SELECT 'X'
FROM customer_lapses
WHERE mem_reg_member_id = mere.member_id
AND mem_reg_registration_id = mere.registration_id
AND suspend_lapse_ind = 'L'
AND reinstatement_ind = 'N'
AND lapse_effective_date <= NVL(i_reportdate ,Sysdate)
)
AND NOT EXISTS
( SELECT 'X'
FROM customer_lapses
WHERE member_product_id = mepr.member_product_id
AND suspend_lapse_ind = 'L'
AND reinstatement_ind = 'N'
AND lapse_effective_date <= NVL(i_reportdate ,Sysdate)
UNION
SELECT 'X'
FROM customer_lapses
WHERE cust_prod_contract_pk = mepr.contract_pk
AND cust_prod_product_id = mepr.product_id
AND suspend_lapse_ind = 'L'
AND reinstatement_ind = 'N'
AND lapse_effective_date <= NVL(i_reportdate ,Sysdate)
)
Group BY 11
,'SQ'
,grou.GROUP_ID -- GROUP_ID
,grou.group_name -- group_name
,intm.intermediary_id -- intermediary_id --R3352 AUS Regulatory added new field
,intm.intermediary_name -- intermediary_name
,regi.registration_id -- registration_id
,mere.member_id -- member_id
,memb.title_code -- title_code
,memb.given_name||' '||memb.family_name -- member_name
--,mech.birth_date birth_date
,mere.company_employee_ref -- company_employee_ref
,memb.orig_risk_start_date -- orig_risk_start_date
,mere.original_bi_joining_date -- orig_joining_date
,mepr.member_product_id -- member_product_id
,mepr.member_product_risk_start_date -- mp_risk_start_date
,mepr.product_id -- product_id
,INITCAP(prod.product_name) -- product_name
,cont.currency_code
,mere.customer_status_code

Which version of Oracle Reports ?
The scalar subqueries syntax came in around Oracle 8/8i, but the development of Oracle reports stopped sometime around the stone-age. A lot of the enhanced SQL syntax of the last 10+ years hasn't made it in.
If you can create the bulk of the query as a view in the database, and just select from the view in the report, then you have more flexibility

Related

How to modify column data-type while column is in used

I have problem while I use SELECT query. Unfortunettly, the ID is store as VARCHAR which is big mistake and right now I have problem in following function
FUNCTION GET_SUB_PROJECTS(p_currentUserId IN VARCHAR,p_projectId IN INT)
RETURN SYS_REFCURSOR IS
rc SYS_REFCURSOR;
-- getSubProject
BEGIN
OPEN rc FOR
SELECT
p.*,
a.number_ AS activityNumber,
a.description AS activityDescription
FROM
projects p
LEFT JOIN
project_users_schedule_dates pusd
ON
pusd.ProjectID = p.ProjectID AND pusd.UserID = p_currentUserId
LEFT JOIN
activities a
ON
a.id = p.activity
LEFT JOIN
responsible_persons rp
ON
rp.ProjectID = p.ProjectID AND rp.UserID = p_currentUserId
LEFT JOIN
users u
ON
u.UserID = p_currentUserId
WHERE
(u.User_roleID = 1 AND
p.CustomName LIKE CONCAT((SELECT CustomName FROM projects pr WHERE pr.ProjectID = p_projectId), '%') AND p.ProjectID <> p_projectId)
OR
((
(p.Responsible_person_id = p_currentUserId OR p.Delivery_contact = p_currentUserId OR rp.UserID = p_currentUserId OR (pusd.UserID = p_currentUserId AND SYSTIMESTAMP BETWEEN TO_DATE(pusd.StartDate,'YYYY-MM-DD') AND TO_DATE(pusd.EndDate,'YYYY-MM-DD') + INTERVAL '1' DAY AND
SYSTIMESTAMP BETWEEN TO_DATE(p.StartDate,'YYYY-MM-DD') AND TO_DATE(p.EndDate,'YYYY-MM-DD') + INTERVAL '1' DAY))
)
AND
p.CustomName LIKE CONCAT((SELECT CustomName FROM projects pr WHERE pr.ProjectID = p_projectId), '%') AND p.ProjectID <> p_projectId)
ORDER BY p.CustomName;
RETURN rc;
END GET_SUB_PROJECTS;
When I call function it needs to return data, but it doesn't. Somehow, here p.Responsible_person_id and p.Delivery_contact needs to be NUMBER but somehow it is VARCHAR
When I call function I use
SELECT PROJECT_PACKAGE.GET_SUB_PROJECTS('199',141) FROM DUAL
I found one solution to modify but It throw me error like
Error report -
ORA-01439: column to be modified must be empty to change datatype
01439. 00000 - "column to be modified must be empty to change datatype"
What to do in this situation ? What is the best method to solve this issue ?
You can change the data type of a column online using dbms_redefinition
create table t (
c1 varchar2(10)
primary key
);
create table t_new (
c1 number(10, 0)
primary key
);
insert into t values ( '1.0000' );
commit;
begin
dbms_redefinition.start_redef_table (
user, 't', 't_new',
col_mapping => 'to_number ( c1 ) c1',
options_flag => dbms_redefinition.cons_use_rowid
);
end;
/
exec dbms_redefinition.sync_interim_table ( user, 't', 't_new' );
exec dbms_redefinition.finish_redef_table ( user, 't', 't_new' );
desc t
Name Null? Type
C1 NOT NULL NUMBER(10)
select * from t;
C1
1
There are also options to copy constraints, triggers, indexes, etc. automatically in this process.

why SSRS asking to Define query parameters when already defined?

I have the below query which is working well in SQL. But when I use this query in ssrs(Visual studio 2015) it is giving me error saying define query parameters. I have already defined values for parametes but still getting the error. I feel something from the SQL query which s not getting supported in SSRS. Can anyone help?
[![SET FMTONLY OFF
USE GODSDB
declare
#start date = getdate() - 100
, #end date = getdate()
drop table #CallLog
declare #code varchar(max), #TableName varchar(max), #SeverName varchar(max)
--IF object_id('tempdb..#CallLog') IS NOT NULL DROP TABLE #CallLog
CREATE TABLE #CallLog (
\[JurisdictionShortIdentifier\] VARCHAR(100),
\[ContractCallLogOID\] INT,
\[ContractCallLogProcessQueueOID\] INT,
\[ContractOID\] INT,
\[CallDate\] DATETIME,
\[CallHandledBy\] VARCHAR(60),
\[CallLogOldGreenUnit\] INT,
\[CallLogNewGreenUnit\] INT,
\[Comment\] VARCHAR(7500)
)
set #TableName = '#CallLog'
set #SeverName = 'BA_GBASSTOCSISDB' -- sp_linkedservers
set #code = '
;with XMLNAMESPACES(DEFAULT ''http://tempuri.org/GEOUnit.xsd'')
select
ccl.JurisdictionShortIdentifier,
ccl.ContractCallLogOID,
que.ContractCallLogProcessQueueOID,
ccl.ContractOID,
ccl.db_insertDate as CallDate,
ccl.db_insertBy as CallHandledBy,
convert(xml, que.XMLString).value(''(/GEOUnit/GreenPowerUnits/GreenPowerUnitsOld)\[1\]'',''int'') as CallLogOldGreenUnit,
convert(xml, que.XMLString).value(''(/GEOUnit/GreenPowerUnits/GreenPowerUnitsNew)\[1\]'',''int'') as CallLogNewGreenUnit,
cmt.Comment
from CSISDB.dbo.ContractCallLog as ccl (nolock)
left join CSISDB.dbo.ContractCallLogProcessQueue as que (nolock) on ccl.ContractCallLogOID = que.ContractCallLogOID
left join CSISDB.dbo.Comment as cmt (nolock) on ccl.ContractCallLogOID = cmt.FKObjectOID and cmt.FKTableObjectOID = 1008
where 1 = 1
and ccl.ContractCallLogStatusIdentifier in (''GMOD'', ''GUS'', ''GI'')
and ccl.ContractCallLogReasonIdentifier in (''Changed'', ''GEOR'', ''NULL'', ''GEO'', ''GEO0'', ''GEO1'', ''GEO3'', ''GEO2'', ''CDR'', ''GEO4'', ''GEO5'', ''JUST GREEN adder'', ''JustGreen'')
--and ccl.JurisdictionShortIdentifier = ''AG''
and ccl.SourceSystemIdentifier = ''GBASS''
and ccl.db_insertDate between #start and #end
--and ccl.ContractCallLogOID = 57131879 --> TEST CASE
'
set #code = replace(#code, '#start', '''' + convert(varchar, convert(date, #start, 101)) + '''')
set #code = replace(#code, '#end', '''' + convert(varchar, convert(date, dateadd(day, 1, #end), 101)) + '''')
set #code = concat('insert into ', #TableName, ' select * from openquery (', #SeverName, ', ''' , replace(#code, '''', '''''') , ''')')
print #code
exec(#code)
-- select * from #CallLog where ContractCallLogOID = 57707501
-- some call log have multiple process queues, delete the process queues that don't is not modifying the geo units
delete a
from #CallLog as a
inner join #CallLog as b on a.ContractCallLogOID = b.ContractCallLogOID
and a.ContractCallLogProcessQueueOID != b.ContractCallLogProcessQueueOID
and a.CallLogNewGreenUnit is null
and b.CallLogNewGreenUnit is not null
--select * from #CallLog
select
ccl.JurisdictionShortIdentifier,
ccl.ContractCallLogOID,
ccl.ContractCallLogProcessQueueOID,
cnt.RtlrContractIdentifier,
ccl.ContractOID,
cst.ContractStatusIdentifier as ContractStatus,
ccl.CallLogOldGreenUnit,
ccl.CallLogNewGreenUnit,
cur.GreenLevelIndicator as CurrentGreenUnit,
cur.db_insertDate as GreenUnitLastUpdateDate,
cur.db_insertBy as GreenUnitLastUpdateBy,
ccl.CallDate,
ccl.CallHandledBy,
ccl.Comment
from #CallLog as ccl
inner join Contract as cnt (nolock) on ccl.ContractOID = cnt.ContractOID
and ccl.CallLogOldGreenUnit != ccl.CallLogNewGreenUnit
inner join ContractState as cst (nolock) on cnt.ContractOID = cst.ContractOID
left join ContractGreenContent as cur (nolock) on cnt.ContractOID = cur.ContractOID
and isnull(cur.EffectiveEndDate, dateadd(day, 1, getdate())) >= getdate()
left join ContractGreenContent as his (nolock) on cnt.ContractOID = his.ContractOID
and ccl.CallLogNewGreenUnit = his.GreenLevelIndicator
and his.db_insertDate between dateadd(day, -1, ccl.CallDate) and dateadd(day, 1, ccl.CallDate)
where his.ContractGreenContentOID is null
--select * from #CallLog
union all
select
ccl.JurisdictionShortIdentifier,
ccl.ContractCallLogOID,
ccl.ContractCallLogProcessQueueOID,
cnt.RtlrContractIdentifier,
ccl.ContractOID,
cst.ContractStatusIdentifier as ContractStatus,
ccl.CallLogOldGreenUnit,
ccl.CallLogNewGreenUnit,
cur.GreenLevelIndicator as CurrentGreenUnit,
cur.db_insertDate as GreenUnitLastUpdateDate,
cur.db_insertBy as GreenUnitLastUpdateBy,
ccl.CallDate,
ccl.CallHandledBy,
ccl.Comment
from #CallLog as ccl
inner join Contract as cnt (nolock) on ccl.ContractOID = cnt.ContractOID
and isnull(ccl.CallLogOldGreenUnit, 0) = isnull(ccl.CallLogNewGreenUnit, 0)
inner join ContractState as cst (nolock) on cnt.ContractOID = cst.ContractOID
left join ContractGreenContent as cur (nolock) on cnt.ContractOID = cur.ContractOID
and isnull(cur.EffectiveEndDate, dateadd(day, 1, getdate())) >= getdate()
SET FMTONLY ON][1]][1]
Make sure your parameter names and SQL variables are all spelled exactly the same, they are case sensitive.
Also try declaring each variable on it own line with its own DECLARE statement. I've seen this fix this issue 'sometimes'
Your parameters are inside your #SQL query variable. The server that you are running the OPENQUERY from doesn't recognize the parameters since they were declared on another server.
Put the parameter declarations inside your SQL variable:
set #code = '
declare
#start date = getdate() - 100
, #end date = getdate()
...

Looking for whether a row exists in a subquery

Spoiler alert: I am fairly new to Oracle.
I have four tables: enrollments, courses/sections, standards, and grades.
We are running Honor Roll. I have queries on the first three tables that add various constraints needed to meet honor roll requirements. Then we look at the grades table. If they have a valid enrollment, in a valid course, meeting valid standards, then count up their scores. If their score qty meets thresholds, then they get Honors.
This code is not optimized, and likely can be done in a far better/more compact way I'm sure -- however, it only gets run a few times a year, so I'm willing to trade off optimization in order to increase human readability, so that I can continue to learn the fundamentals. So far I have:
WITH validCC (SELECT CC.ID AS CCID,
CC.STUDENTID AS STUDENTID,
CC.SECTIONID AS SECTIONID,
CC.TERMID AS TERMID,
STUDENTS.DCID AS STUDENTSDCID
FROM CC
INNER JOIN STUDENTS ON CC.STUDENTID = STUDENTS.ID
WHERE TERMID in (2700,2701)
AND CC.SCHOOLID = 406;
), --end validCC
validCrsSect (SELECT SECTIONS.ID AS SECTIONID,
SECTIONS.DCID AS SECTIONSDCID,
SECTIONS.EXCLUDEFROMHONORROLL AS SECTHR,
COURSES.COURSE_NUMBER AS COURSE_NUMBER,
COURSES.COURSE_NAME AS COURSE_NAME,
COURSES.EXCLUDEFROMHONORROLL AS CRSHR
FROM SECTIONS
INNER JOIN COURSES ON SECTIONS.COURSE_NUMBER = COURSES.COURSE_NUMBER AND SECTIONS.SCHOOLID = COURSES.SCHOOLID
WHERE SECTIONS.TERMID IN (2700,2701)
AND SECTIONS.SCHOOLID = 406
AND SECTIONS.EXCLUDEFROMHONORROLL = 0
AND COURSES.EXCLUDEFROMHONORROLL = 0
), --end validCrsSect
validStandard (SELECT STANDARDID,
IDENTIFIER,
TRANSIENTCOURSELIST
FROM STANDARD
WHERE isActive = 1
AND YEARID = 27
AND ( instr (STANDARD.identifier, 'MHS.TS', 1 ,1) > 0 --Is a valid standard for this criteria: MHS TS
or STANDARD.identifier = 'MHTC.TS.2' --or MHTC TS
or STANDARD.identifier = 'MHTC.TS.4' )
), --end validStandard
--sgsWithChecks (
SELECT sgs.STANDARDGRADESECTIONID AS SGSID,
sgs.STUDENTSDCID as STUDENTSDCID,
sgs.STANDARDID AS STANDARDID,
sgs.STORECODE AS STORECODE,
sgs.SECTIONSDCID AS SECTIONSDCID,
sgs.YEARID AS YEARID,
sgs.STANDARDGRADE AS STANDARDGRADE,
(select count(CCID) from validCC INNER JOIN STANDARDGRADESECTION sgs ON sgs.STUDENTSDCID = validCC.STUDENTSDCID and sgs.SECTIONSDCID = validCC.SECTIONID) as CC_OK,
(select count(SECTIONID) from validCrsSection INNER JOIN STANDARDGRADESECTION sgs ON sgs.SECTIONSDCID = validCrsSect.SECTIONSDCID) AS CRS_OK,
(select count(STANDARDID) from validStandard INNER JOIN STANDARDGRADESECTION sgs ON sgs.STANDARDID = validStandard.STANDARDID) AS STD_OK
FROM STANDARDGRADESECTION sgs
The purpose of putting the 'OK' columns in the vGrades table is because the final SELECT (not included) goes through and counts up the instances of certain scores filtering by the checks.
Frustratingly, there are two IDs in both the students table and the sections table (and it's not the same data). So when I go to link everything, some tables use ID as the FK, others use DCID as the FK; and I have to pull in an extra table to make that conversion. Makes the joins more fun that way I guess.
Each individual query works on its own, but I can't get the final select count() to work to pull their data. I tried embedding the initial queries as subqueries, but I couldn't pass the studentid into them, and it would run that query for each student, instead of once at the beginning.
My current error is:
Error starting at line : 13 in command -
SECTIONS.DCID AS SECTIONSDCID,
Error report -
Unknown Command
However before it was saying unknown table and referencing the last line of the join statement. All the table names are valid.
Thoughts?
I replaced the INNER JOIN with a simple WHERE condition. This seems to work.
(SELECT COUNT (CCID) FROM validCC WHERE sgs.STUDENTSDCID = validCC.STUDENTSDCID and sgs.SECTIONSDCID = validCC.SECTIONID) as CC_OK,
(SELECT COUNT (SECTIONID) FROM validCrsSect WHERE sgs.SECTIONSDCID = validCrsSect.SECTIONSDCID) AS CRS_OK,
(SELECT COUNT (STANDARDID) FROM validStandard WHERE sgs.STANDARDID = validStandard.STANDARDID) AS STD_OK
I removed the stray comma at the end of validStandard and replaced from validCrsSection with from validCrsSect (assuming it was meant to refer to that WITH clause and there isn't another validCrsSection table). I am also guessing that the counts are meant to be keyed to the current sgs row and not counts of the whole table. I make it this:
with validcc as
( select cc.id as ccid
, cc.studentid
, cc.sectionid
, cc.termid
, st.dcid as studentsdcid
from cc
join students st on st.id = cc.studentid
where cc.termid in (2700, 2701)
and cc.schoolid = 406
)
, validcrssect as
( select s.id as sectionid
, s.dcid as sectionsdcid
, s.excludefromhonorroll as secthr
, c.course_number
, c.course_name
, c.excludefromhonorroll as crshr
from sections s
join courses c
on c.course_number = s.course_number
and c.schoolid = s.schoolid
where s.termid in (2700, 2701)
and s.schoolid = 406
and s.excludefromhonorroll = 0
and c.excludefromhonorroll = 0
)
, validstandard as
( select standardid
, identifier
, transientcourselist
from standard
where isactive = 1
and yearid = 27
and ( instr(standard.identifier, 'MHS.TS', 1, 1) > 0
or standard.identifier in ('MHTC.TS.2','MHTC.TS.4') )
)
select sgs.standardgradesectionid as sgsid
, sgs.studentsdcid
, sgs.standardid
, sgs.storecode
, sgs.sectionsdcid
, sgs.yearid
, sgs.standardgrade
, ( select count(*) from validcc
where validcc.studentsdcid = sgs.studentsdcid
and validcc.sectionid = sgs.sectionsdcid ) as cc_ok
, ( select count(*) from validcrssect
where validcrssect.sectionsdcid = sgs.sectionsdcid ) as crs_ok
, ( select count(*) from validstandard
where validstandard.standardid = sgs.standardid ) as std_ok
from standardgradesection sgs;
This works with the six table definitions reverse-engineered as:
create table students
( id integer not null
, dcid integer );
create table cc
( id integer
, studentid integer
, sectionid integer
, termid integer
, schoolid integer );
create table courses
( course_number integer
, course_name varchar2(30)
, excludefromhonorroll integer
, schoolid integer );
create table sections
( id integer not null
, dcid integer
, excludefromhonorroll integer
, termid integer
, schoolid integer
, course_number integer );
create table standard
( standardid integer
, identifier varchar2(20)
, transientcourselist varchar2(50)
, isactive integer
, yearid integer );
create table standardgradesection
( standardgradesectionid integer
, studentsdcid integer
, standardid integer
, storecode integer
, sectionsdcid integer
, yearid integer
, standardgrade integer );

oracle SQL procedure error not ended properly

I am trying to select the total number of each value in column paxtype with the following letters m,f,i,c but my error is sql not ended properly
(select b.PAXTYPE from xxxx b, xxx a)
(case b.PAXTYPE
when 'M' then count('M')
when 'F' then count('F')
when 'I' then count('I')
when 'C' then count('C')
END)
where a.date_key=to_char(b.FLIGHTDATE,'RRRRMMDD')
and a.FLTNUM_KEY= trim(substr(b.flightnumber,3))
and a.origin=b.frm
and a.destination=b.too
--and a.date_key=20170801
--and fightnumber = '100'
and trim(a.cancelled) is null
and rownum = 1
)
Firstly You are not using the correct sql syntax. Also, there are several other problems with your query.
Table names should come after columns in select .
You need to use group by since you need count
There is no need for CASE block
why is ROWNUM = 1 required?
This query should work fine for your requirement.
SELECT b.PAXTYPE, COUNT (b.PAXTYPE)
FROM xxxx b, xxx a
WHERE a.date_key = TO_CHAR (b.FLIGHTDATE, 'RRRRMMDD')
AND a.FLTNUM_KEY = TRIM (SUBSTR (b.flightnumber, 3))
AND a.origin = b.frm
AND a.destination = b.too
--and a.date_key=20170801
--and fightnumber = '100'
AND TRIM (a.cancelled) IS NULL
--and rownum = 1 # Why was it required?
GROUP BY b.PAXTYPE;
Additionally, If you need only the counts for M,F,I,C then add AND b.PAXTYPE IN ('M','F','I','C') before group by

ORA-01427: Subquery returns more than one row

When I execute the query below, I get the message like this: "ORA-01427: Sub-query returns more than one row"
Define REN_RunDate = '20160219'
Define MOP_ADJ_RunDate = '20160219'
Define RID_RunDate = '20160219'
Define Mbr_Err_RunDate = '20160219'
Define Clm_Err_RunDate = '20160219'
Define EECD_RunDate = '20160219'
select t6.Member_ID, (Select 'Y' from MBR_ERR t7 where t7.Member_ID = t6.Member_ID and t7.Rundate = &Mbr_Err_RunDate ) Mbr_Err,
NVL(Claim_Sent_Amt,0) Sent_Claims, Rejected_Claims,Orphan_Claim_Amt,Claims_Accepted, MOP_Adj_Sent Sent_MOP_Adj,Net_Sent,
(Case
When Net_Sent < 45000 then 0
When Net_Sent > 25000 then 20500
Else
Net_Sent - 45000
End
)Net_Sent_RI,
' ' Spacer,
Total_Paid_Claims CMS_Paid_Claims, MOP_Adjustment CM_MOP_Adj, MOP_Adjusted_Paid_claims CM_Net_Claims, Estimated_RI_Payment CM_RI_Payment
from
(
select NVL(t3.Member_ID,t5.Member_ID)Member_ID, t3.Claim_Sent_Amt, NVL(t4.Reject_Claims_Amt,0) Rejected_Claims, NVL( t8.Orphan_Amt,0) Orphan_Claim_Amt,
(t3.Claim_Sent_Amt - NVL(t4.Reject_Claims_Amt,0) - NVL(t8.Orphan_Amt,0)) Claims_Accepted,
NVL(t2.MOP_Adj_Amt,0) MOP_Adj_Sent ,
( (t3.Claim_Sent_Amt - NVL(t4.Reject_Claims_Amt,0)) - NVL(t2.MOP_Adj_Amt,0) - NVL(t8.Orphan_Amt,0) ) Net_Sent,
t5.Member_ID CMS_Mbr_ID,t5.Total_Paid_Claims,t5.MOP_Adjustment, t5.MOP_Adjusted_Paid_Claims, t5.Estimated_RI_Payment
From
(
Select t1.Member_ID, Sum( t1.Paid_Amount) Claim_Sent_Amt
From RENS t1
where t1.rundate = &REN_RunDate
group by t1.Member_ID
) t3
Left Join MOP_ADJ t2
on (t3.Member_ID = t2.Member_ID and t2.rundate = &MOP_ADJ_RunDate)
Left Join
(select Member_ID, sum(Claim_Total_Paid_Amount) Reject_Claims_Amt from CLAIM_ERR
where Rundate = &Claim_Err_RunDate
and Claim_Total_Paid_Amount != 0
Group by member_ID
)t4
on (t4.Member_ID = t3.Member_ID )
Full Outer Join
(
select distinct Member_ID,Total_Paid_Claims,MOP_Adjustment,MOP_Adjusted_Paid_Claims, Estimated_RI_Payment
from RID
where Rundate = &RID_RunDate
and Estimated_RI_Payment != 0
)t5
On(t5.Member_ID = t3.Member_ID)
Left Outer Join
(
select Member_ID, Sum(Claim_Paid_Amount) Orphan_Amt
From EECD
where RunDate = &EECD_RunDate
group by Member_ID
)t8
On(t8.Member_ID = t3.Member_ID)
)t6
order by Member_ID
You have this expression among the select columns (at the top of your code):
(Select 'Y' from MBR_ERR t7 where t7.Member_ID = t6.Member_ID
and t7.Rundate = &Mbr_Err_RunDate ) Mbr_Err
If you want to select the literal 'Y', then just select 'Y' as Mbr_Err. If you want to select either 'Y' or null, depending on whether the the subquery returns exactly one row or zero rows, then write it that way.
I suspect this subquery (or perhaps another one in your code, used in a similar way) returns more than one row - in which case you will get exactly the error you got.

Resources