SYS_CONNECT_BY_PATH with CLOB - sql
I have an ORA-01489: result of string concatenation is too long error executing this query on a Oracle Database 11g Enterprise Edition Release 11.2.0.4.0 - 64bit Production, PL/SQL Release 11.2.0.4.0 - Production, CORE 11.2.0.4.0 Production, TNS for Linux: Version 11.2.0.4.0 - Production, NLSRTL Version 11.2.0.4.0 - Production:
SELECT "USER_PRIMARY_UNIT","LOGIN","FIRST_NAME","LAST_NAME","UNIT_ROLE"
FROM (
SELECT user_primary_unit,login, first_name, last_name,
LTRIM(MAX(SYS_CONNECT_BY_PATH(rights,' / '))
KEEP (DENSE_RANK LAST ORDER BY curr),' / ') AS UNIT_ROLE
FROM
(SELECT login,
first_name,
last_name,
user_primary_unit,
rights,
ROW_NUMBER() OVER (PARTITION BY login ORDER BY rights) AS curr,
ROW_NUMBER() OVER (PARTITION BY login ORDER BY rights) -1 AS prev
FROM (select member0_.login, member0_.first_name first_name, unit2.unit_name user_primary_unit, member0_.last_name last_name,
CONCAT(CONCAT(unit.unit_name, ' - '), role3_.role_name) rights
from
IOT_DEVICES.t_member member0_
inner join IOT_DEVICES.t_user member0_1_ on member0_.member_id=member0_1_.user_id
inner join IOT_DEVICES.t_playable_role playedrole1_ on member0_.member_id=playedrole1_.user_id
inner join IOT_DEVICES.t_unit_role unitrole2_ on playedrole1_.unit_role_id=unitrole2_.unit_role_id
inner join IOT_DEVICES.t_role role3_ on unitrole2_.role_id=role3_.role_id
inner join IOT_DEVICES.t_unit unit on unitrole2_.unit_id=unit.unit_id
inner join IOT_DEVICES.t_unit unit2 on unit2.unit_id=member0_1_.primary_unit_id
where current_date between playedrole1_.start_date and playedrole1_.end_date
order by unit.unit_name
))
GROUP BY login, first_name, last_name, user_primary_unit
CONNECT BY prev = PRIOR curr AND login = PRIOR login
START WITH curr = 1
)
ORDER BY user_PRIMARY_UNIT, FIRST_NAME, LAST_NAME;
The problem with this query is with the use of CONCAT operator (||). Concat operator returns char1 concatenated with char2. The string returned is in the same character set as char1. So here concat operator is trying to return varchar2, which has limit of 4000 characters and getting exceeded. This problem may also come when we try to CONCAT a VARCHAR2 with CLOB. So here I want simply convert its first string to CLOB and avoid this error. After converting first string to CLOB, CONCAT operator will return string of CLOB type
So I add the TO_CLOB to convert the types but then I have the next error:
ORA-00932: inconsistent datatypes: expected - got CLOB
SELECT "USER_PRIMARY_UNIT","LOGIN","FIRST_NAME","LAST_NAME","UNIT_ROLE"
FROM (
SELECT user_primary_unit,login, first_name, last_name,
LTRIM(MAX(SYS_CONNECT_BY_PATH(rights,' / '))
KEEP (DENSE_RANK LAST ORDER BY curr),' / ') AS UNIT_ROLE
FROM
(SELECT login,
first_name,
last_name,
user_primary_unit,
rights,
ROW_NUMBER() OVER (PARTITION BY login ORDER BY rights) AS curr,
ROW_NUMBER() OVER (PARTITION BY login ORDER BY rights) -1 AS prev
FROM (select member0_.login, member0_.first_name first_name, unit2.unit_name user_primary_unit, member0_.last_name last_name,
TO_CLOB(CONCAT(CONCAT(unit.unit_name, ' - '), role3_.role_name)) rights
from
IOT_DEVICES.t_member member0_
inner join IOT_DEVICES.t_user member0_1_ on member0_.member_id=member0_1_.user_id
inner join IOT_DEVICES.t_playable_role playedrole1_ on member0_.member_id=playedrole1_.user_id
inner join IOT_DEVICES.t_unit_role unitrole2_ on playedrole1_.unit_role_id=unitrole2_.unit_role_id
inner join IOT_DEVICES.t_role role3_ on unitrole2_.role_id=role3_.role_id
inner join IOT_DEVICES.t_unit unit on unitrole2_.unit_id=unit.unit_id
inner join IOT_DEVICES.t_unit unit2 on unit2.unit_id=member0_1_.primary_unit_id
where current_date between playedrole1_.start_date and playedrole1_.end_date
order by unit.unit_name
))
GROUP BY login, first_name, last_name, user_primary_unit
CONNECT BY prev = PRIOR curr AND login = PRIOR login
START WITH curr = 1
)
ORDER BY user_PRIMARY_UNIT, FIRST_NAME, LAST_NAME;
I also tried to use the package Hierarchy defined Here but then I got a ORA-00932: inconsistent datatypes: expected - got CLOB
https://community.oracle.com/thread/965324?start=0&tstart=0
SELECT "USER_PRIMARY_UNIT","LOGIN","FIRST_NAME","LAST_NAME","UNIT_ROLE"
FROM (
SELECT user_primary_unit,login, first_name, last_name,
LTRIM(MAX(hierarchy.branch(level,rights,' / '))
KEEP (DENSE_RANK LAST ORDER BY curr),' / ') AS UNIT_ROLE
FROM
(SELECT login,
first_name,
last_name,
user_primary_unit,
rights,
ROW_NUMBER() OVER (PARTITION BY login ORDER BY rights) AS curr,
ROW_NUMBER() OVER (PARTITION BY login ORDER BY rights) -1 AS prev
FROM (select member0_.login, member0_.first_name first_name, unit2.unit_name user_primary_unit, member0_.last_name last_name,
TO_CLOB(CONCAT(CONCAT(unit.unit_name, ' - '), role3_.role_name)) rights
from
IOT_DEVICES.t_member member0_
inner join IOT_DEVICES.t_user member0_1_ on member0_.member_id=member0_1_.user_id
inner join IOT_DEVICES.t_playable_role playedrole1_ on member0_.member_id=playedrole1_.user_id
inner join IOT_DEVICES.t_unit_role unitrole2_ on playedrole1_.unit_role_id=unitrole2_.unit_role_id
inner join IOT_DEVICES.t_role role3_ on unitrole2_.role_id=role3_.role_id
inner join IOT_DEVICES.t_unit unit on unitrole2_.unit_id=unit.unit_id
inner join IOT_DEVICES.t_unit unit2 on unit2.unit_id=member0_1_.primary_unit_id
where current_date between playedrole1_.start_date and playedrole1_.end_date
order by unit.unit_name
))
GROUP BY login, first_name, last_name, user_primary_unit
CONNECT BY prev = PRIOR curr AND login = PRIOR login
START WITH curr = 1
)
ORDER BY user_PRIMARY_UNIT, FIRST_NAME, LAST_NAME;
Then I tried as well with sys.stragg , but i got a ORA-00978: nested group function without GROUP BY
SELECT "USER_PRIMARY_UNIT","LOGIN","FIRST_NAME","LAST_NAME","UNIT_ROLE"
FROM (
SELECT user_primary_unit,login, first_name, last_name,
LTRIM(MAX(SYS_CONNECT_BY_PATH(rights,' / '))
KEEP (DENSE_RANK LAST ORDER BY curr),' / ') AS UNIT_ROLE
FROM
(SELECT login,
first_name,
last_name,
user_primary_unit,
rights,
ROW_NUMBER() OVER (PARTITION BY login ORDER BY rights) AS curr,
ROW_NUMBER() OVER (PARTITION BY login ORDER BY rights) -1 AS prev
FROM (select member0_.login, member0_.first_name first_name, unit2.unit_name user_primary_unit, member0_.last_name last_name,
sys.stragg(sys.stragg(unit.unit_name || ' - ' || role3_.role_name)) rights
from
IOT_DEVICES.t_member member0_
inner join IOT_DEVICES.t_user member0_1_ on member0_.member_id=member0_1_.user_id
inner join IOT_DEVICES.t_playable_role playedrole1_ on member0_.member_id=playedrole1_.user_id
inner join IOT_DEVICES.t_unit_role unitrole2_ on playedrole1_.unit_role_id=unitrole2_.unit_role_id
inner join IOT_DEVICES.t_role role3_ on unitrole2_.role_id=role3_.role_id
inner join IOT_DEVICES.t_unit unit on unitrole2_.unit_id=unit.unit_id
inner join IOT_DEVICES.t_unit unit2 on unit2.unit_id=member0_1_.primary_unit_id
where current_date between playedrole1_.start_date and playedrole1_.end_date
order by unit.unit_name
))
GROUP BY login, first_name, last_name, user_primary_unit
CONNECT BY prev = PRIOR curr AND login = PRIOR login
START WITH curr = 1
)
ORDER BY user_PRIMARY_UNIT, FIRST_NAME, LAST_NAME;
You can build hierarchy CLOB path with subquery factoring syntax This may run really slow. Consider having two path columns - one for varchar2 result and one for CLOB. Build varchar2 till size allows, and keep NULL in CLOB path, and switch to CLOB when out of varchar2 capacity. This is a different question though.
with
base as (
select
level as id,
case when level > 1 then level - 1 end as parent_id,
dbms_random.string('X', 2000) as val
from dual
connect by level <= 50
),
hier(id, parent_id, val, path) as (
select
b.id,
b.parent_id,
b.val,
to_clob(concat('/', b.val)) as path
from base b
where b.parent_id is null
union all
select
b.id,
b.parent_id,
b.val,
concat(h.path, to_clob(' / '||b.val) )
from base b
join hier h on h.id = b.parent_id
)
select rownum, length(h.path)
from hier h;
ROWNUM LENGTH(H.PATH)
1 2001
2 4004
3 6007
4 8010
5 10013
6 12016
7 14019
8 16022
9 18025
10 20028
11 22031
12 24034
13 26037
14 28040
15 30043
16 32046
17 34049
18 36052
19 38055
20 40058
21 42061
22 44064
23 46067
24 48070
25 50073
26 52076
27 54079
28 56082
29 58085
30 60088
31 62091
32 64094
33 66097
34 68100
35 70103
36 72106
37 74109
38 76112
39 78115
40 80118
41 82121
42 84124
43 86127
44 88130
45 90133
46 92136
47 94139
48 96142
49 98145
50 100148
You might found this page, because you're trying to aggregate strings longer than 4000 characters and remembered the different techniques.
If so, I created a small example, based on #B Samedi's answer to help you out, when you're not able to use user defined aggregates
with dummy_text as (
select 'teststring ' || rownum str from dual connect by rownum < 2
)
, indexed_strings as (
select str, row_number() over (order by 'x') rn, ',' separator from dummy_text
)
, hier (str, lvl) as (
select to_clob(i.str), rn from indexed_strings i where rn = (select max(rn) from indexed_strings)
union all
select concat(to_clob(concat(i.str, i.separator)), h.str), h.lvl - 1 from indexed_strings i join hier h on h.lvl - 1 = i.rn
)
select str from hier where lvl = 1
Related
Oracle - ORA-00907: missing right parenthesis
I just can't find what is wrong here. Trying to select path to the article pictures. ORA-00907: missing right parenthesis select artnr, listagg(path, bildnr '.' filtyp) within group (order by bildnr) as sökväg from kund where knr in (select knr from kundorder where ordnr in (select ordnr from orderrad where artnr in (select artnr from artikel where bildnr in (select bildnr from artikelbild)))) order by artnr;
Obvious error is in listagg (missing concatenation): No : listagg (path, bildnr '.' filtyp) Yes: listagg (PATH, bildnr || '.' || filtyp) The rest should be OK (as far as syntax is concerned; can't tell whether query will (or will not) return what you want). Also, perhaps you'd rather switch to JOINs instead of using bunch of nested subqueries, e.g. SELECT u.artnr, LISTAGG (u.PATH, u.bildnr || '.' || u.filtyp) WITHIN GROUP (ORDER BY u.bildnr) AS sokvag FROM kund u JOIN kundorder o ON u.knr = o.knr JOIN orderrad r ON r.ordnr = o.ordnr JOIN artikel a ON a.artnr = r.artnr JOIN artikelbild b ON b.bildnr = a.bildnr ORDER BY u.artnr; As of ORA-30496: Argument should be a constant: apparently, that's true. Code you'd like to run: SQL> select listagg(e.ename, e.job ||'.'|| to_char(e.deptno)) 2 within group (order by null) result 3 from emp e 4 where rownum <= 3; select listagg(e.ename, e.job ||'.'|| to_char(e.deptno)) * ERROR at line 1: ORA-30496: Argument should be a constant. Let's try to fool Oracle and "prepare" the separator: SQL> with temp as 2 (select e.ename, e.job ||'.'||to_char(e.deptno) separator 3 from emp e 4 where rownum <= 3 5 ) 6 select listagg(t.ename, t.separator) 7 within group (order by null) 8 from temp t; select listagg(t.ename, t.separator) * ERROR at line 6: ORA-30496: Argument should be a constant. Still no luck. But if a separator really is a constant (comma in my example), then it works: SQL> select listagg(e.ename ||': ' || e.job, ', ') 2 within group (order by null) result 3 from emp e 4 where rownum <= 3; RESULT ------------------------------------------------------------------------ ALLEN: SALESMAN, SMITH: CLERK, WARD: SALESMAN SQL>
concatenation code column not found in a table using sql
I have a table with few columns and I am trying to concatenate the code column with rank. But it throws me an error by saying code not found, this is in the concatenation I am doing with rank and code. The code column is a calculated column as you can see from the query. Could anyone please point me where I am doing a mistake? table mm ID cal_dtm rank milestone_hier_onb tr CNT 1/31/2020 1 RFR EEZ table dd ID frs lst frst lst_s cal CNT 6/20/2018 6/28/2018 6/28/2018 1/31/2020 Query WITH r AS ( SELECT dd.ID, dd.frs, dd.lst, dd.frst, dd.lst_s, dd.cal_dtm, mm.tr, mm.ipf_rank, mm.milestone_hier_onb FROM dos dd LEFT JOIN plw mm ON dd.ID = mm.ID AND dd.cal_dtm = mm.cal_dtm ) SELECT * FROM ( SELECT r.ID, r.cal_dtm, 'lp' AS code, r.lst_s AS planned, r.lst AS actual, r.tr, r.ipf_rank AS rank, r.milestone_hier_onb AS onb, * * CONCAT ( r.ipf_rank, code ) AS milestone_label * * FROM r WHERE r.lst IS NOT NULL UNION SELECT r.ID, r.cal_dtm, 'fp' AS code, r.frst AS planned, r.frs AS actual, r.tr, r.ipf_rank AS rank, r.milestone_hier_onb AS onb, * * CONCAT ( r.ipf_rank, code ) AS milestone_label * * FROM r WHERE r.frs IS NOT NULL ) ORDER BY ID, cal_dtm, code Expected output ID Cal code pl Al tr milestone_label rank onb CNT 1/31/2020 lp 6/28/2018 6/28/2018 lp 1 1 CNT 1/31/2020 fp 6/20/2018
You can't use CODE like that; it is a constant so - concatenate that constant, e.g. ... 'lp' as code, r.ipf_rank || 'lp' as milestone_label ... How to add space? r.ipf_rank ||' '|| 'lp' as milestone_label or r.ipf_rank ||' lp' as milestone_label
Let try: remove order by add alias **concat( r.ipf_rank, code) => **concat( r.ipf_rank, r.code)
Recursive/hierarchical query in BigQuery
I have a recursion/hierarchical problem that I'm trying to figure out in BigQuery. I have a list of employees and each employee has a manager ID. I need to be able to enter a single Employee_ID and return an array of every person beneath them. CREATE TABLE p_RLS.testHeirarchy ( Employee_ID INT64, Employee_Name STRING, Position STRING, Line_Manager_ID INT64 ); INSERT INTO p_RLS.testHeirarchy (Employee_ID, Employee_Name, Position, Line_Manager_ID) VALUES(1,'Joe','Worker',11), (2,'James','Worker',11), (3,'Jack','Worker',11), (4,'Jill','Worker',12), (5,'Jan','Worker',12), (6,'Jacquie','Worker',13), (7,'Joaquin','Worker',14), (8,'Jeremy','Worker',14), (9,'Jade','Worker',15), (10,'Jocelyn','Worker',15), (11, 'Bob', 'Store Manager',16), (12, 'Bill', 'Store Manager',16), (13, 'Barb', 'Store Manager',16), (14, 'Ben', 'Store Manager',17), (15, 'Burt', 'Store Manager',17), (16, 'Sally','Group Manager',18), (17, 'Sam','Group Manager',19), (18, 'Anna', 'Ops Manager',20), (19, 'Amy', 'Ops Manager',20), (20, 'Zoe', 'State Manager', NULL); My desired output would resemble: SELECT 20 as Employee_ID, [19,18,17,16,15,14,13,12,11,10,9,8,7,6,5,4,3,2,1] as Reports; SELECT 11 as Employee_ID, [3,2,1] as Reports; SELECT 1 as Employee_ID, [] as Reports; I have got the following working but it seems very ugly/inconvenient and doesn't support unlimited levels: WITH test as ( SELECT L0.Employee_ID, L0.Employee_Name, L0.Position, L0.Line_Manager_ID, ARRAY_AGG(DISTINCT L1.Employee_ID IGNORE NULLS) as Lvl1, ARRAY_AGG(DISTINCT L2.Employee_ID IGNORE NULLS) as Lvl2, ARRAY_AGG(DISTINCT L3.Employee_ID IGNORE NULLS) as Lvl3, ARRAY_AGG(DISTINCT L4.Employee_ID IGNORE NULLS) as Lvl4, ARRAY_AGG(DISTINCT L5.Employee_ID IGNORE NULLS) as Lvl5, ARRAY_AGG(DISTINCT L6.Employee_ID IGNORE NULLS) as Lvl6, ARRAY_AGG(DISTINCT L7.Employee_ID IGNORE NULLS) as Lvl7 FROM p_RLS.testHeirarchy as L0 LEFT OUTER JOIN p_RLS.testHeirarchy L1 ON L0.Employee_ID = L1.Line_Manager_ID LEFT OUTER JOIN p_RLS.testHeirarchy L2 ON L1.Employee_ID = L2.Line_Manager_ID LEFT OUTER JOIN p_RLS.testHeirarchy L3 ON L2.Employee_ID = L3.Line_Manager_ID LEFT OUTER JOIN p_RLS.testHeirarchy L4 ON L3.Employee_ID = L4.Line_Manager_ID LEFT OUTER JOIN p_RLS.testHeirarchy L5 ON L4.Employee_ID = L5.Line_Manager_ID LEFT OUTER JOIN p_RLS.testHeirarchy L6 ON L5.Employee_ID = L6.Line_Manager_ID LEFT OUTER JOIN p_RLS.testHeirarchy L7 ON L6.Employee_ID = L7.Line_Manager_ID WHERE L0.Employee_ID = 16 GROUP BY 1,2,3,4) SELECT Employee_ID, ARRAY_CONCAT( IFNULL(Lvl1,[]), IFNULL(Lvl2,[]), IFNULL(Lvl3,[]), IFNULL(Lvl4,[]), IFNULL(Lvl5,[]), IFNULL(Lvl6,[]), IFNULL(Lvl7,[])) as All_reports FROM test Is there a better way to do this? Is a recursive approach possible in BigQuery?
Recursive CTE was recently introduced ! This makes things so much easier with recursive iterations as ( select line_manager_id, employee_id, 1 pos from your_table union all select b.line_manager_id, a.employee_id, pos + 1 from your_table a join iterations b on b.employee_id = a.line_manager_id ) select line_manager_id, string_agg('' || employee_id order by pos, employee_id desc) as reports_as_list from iterations where not line_manager_id is null group by line_manager_id order by line_manager_id desc If applied to sample data in question - output is
Below is for BigQuery Standard SQL DECLARE rows_count, run_away_stop INT64 DEFAULT 0; CREATE TEMP TABLE initialData AS WITH input AS ( SELECT 1 Employee_ID,'Joe' Employee_Name,'Worker' Position,11 Line_Manager_ID UNION ALL SELECT 2,'James','Worker',11 UNION ALL SELECT 3,'Jack','Worker',11 UNION ALL SELECT 4,'Jill','Worker',12 UNION ALL SELECT 5,'Jan','Worker',12 UNION ALL SELECT 6,'Jacquie','Worker',13 UNION ALL SELECT 7,'Joaquin','Worker',14 UNION ALL SELECT 8,'Jeremy','Worker',14 UNION ALL SELECT 9,'Jade','Worker',15 UNION ALL SELECT 10,'Jocelyn','Worker',15 UNION ALL SELECT 11, 'Bob', 'Store Manager',16 UNION ALL SELECT 12, 'Bill', 'Store Manager',16 UNION ALL SELECT 13, 'Barb', 'Store Manager',16 UNION ALL SELECT 14, 'Ben', 'Store Manager',17 UNION ALL SELECT 15, 'Burt', 'Store Manager',17 UNION ALL SELECT 16, 'Sally','Group Manager',18 UNION ALL SELECT 17, 'Sam','Group Manager',19 UNION ALL SELECT 18, 'Anna', 'Ops Manager',20 UNION ALL SELECT 19, 'Amy', 'Ops Manager',20 UNION ALL SELECT 20, 'Zoe', 'State Manager', NULL ) SELECT * FROM input; CREATE TEMP TABLE ttt AS SELECT Line_Manager_ID, ARRAY_AGG(Employee_ID) Reports FROM initialData WHERE NOT Line_Manager_ID IS NULL GROUP BY Line_Manager_ID; LOOP SET (run_away_stop, rows_count) = (SELECT AS STRUCT run_away_stop + 1, COUNT(1) FROM ttt); CREATE OR REPLACE TEMP TABLE ttt1 AS SELECT Line_Manager_ID, ARRAY(SELECT DISTINCT Employee_ID FROM UNNEST(Reports) Employee_ID ORDER BY Employee_ID DESC) Reports FROM ( SELECT Line_Manager_ID, ARRAY_CONCAT_AGG(Reports) Reports FROM ( SELECT t2.Line_Manager_ID, ARRAY_CONCAT(t1.Reports, t2.Reports) Reports FROM ttt t1, ttt t2 WHERE (SELECT COUNTIF(t1.Line_Manager_ID = Employee_ID) FROM UNNEST(t2.Reports) Employee_ID) > 0 ) GROUP BY Line_Manager_ID ); CREATE OR REPLACE TEMP TABLE ttt AS SELECT * FROM ttt1 UNION ALL SELECT * FROM ttt WHERE NOT Line_Manager_ID IN (SELECT Line_Manager_ID FROM ttt1); IF (rows_count = (SELECT COUNT(1) FROM ttt) AND run_away_stop > 1) OR run_away_stop > 10 THEN BREAK; END IF; END LOOP; SELECT Employee_ID, ( SELECT STRING_AGG(CAST(Employee_ID AS STRING), ',' ORDER BY Employee_ID DESC) FROM ttt.Reports Employee_ID ) Reports_as_list FROM (SELECT DISTINCT Employee_ID FROM initialData) d LEFT JOIN ttt ON Employee_ID = Line_Manager_ID ORDER BY Employee_ID DESC; with result Row Employee_ID Reports_as_list 1 20 19,18,17,16,15,14,13,12,11,10,9,8,7,6,5,4,3,2,1 2 19 17,15,14,10,9,8,7 3 18 16,13,12,11,6,5,4,3,2,1 4 17 15,14,10,9,8,7 5 16 13,12,11,6,5,4,3,2,1 6 15 10,9 7 14 8,7 8 13 6 9 12 5,4 10 11 3,2,1 11 10 null 12 9 null 13 8 null 14 7 null 15 6 null 16 5 null 17 4 null 18 3 null 19 2 null 20 1 null In case if you need Reports as array - replace last statement in above script with below SELECT Employee_ID, Reports Reports_as_array FROM (SELECT DISTINCT Employee_ID FROM initialData) d LEFT JOIN ttt ON Employee_ID = Line_Manager_ID ORDER BY Employee_ID DESC; Note: depends on level of nesting in your hierarchy - you might need to adjust 10 in OR run_away_stop > 10
To the question: "Is a recursive approach possible in BigQuery?" Yes! Now that BigQuery supports scripting and loops I solved some recursive problems from the Advent of Code with BigQuery: https://towardsdatascience.com/advent-of-code-sql-bigquery-31e6a04964d4 CREATE TEMP TABLE planets AS SELECT 'YOU' planet; LOOP SET steps = steps+1 ; CREATE OR REPLACE TEMP TABLE planets AS SELECT DISTINCT planet FROM ( SELECT origin planet FROM t1 WHERE dest IN (SELECT planet FROM planets) UNION ALL SELECT dest planet FROM t1 WHERE origin IN (SELECT planet FROM planets) ) ; IF 'SAN' IN (SELECT * FROM planets ) THEN LEAVE; END IF; END LOOP ; SELECT steps-2 I would use a similar approach to navigate the graph and annotate all parent relationships. Soon: I'll write a blog post on the specifics of tree traversal to get everyone under x. But this code will help you in the meantime.
Listagg Overflow function implementation (Oracle SQL)
I am using LISTAGG function for my query, however, it returned an ORA-01489: result of string concatenation is too long error. So I googled that error and found out I can use ON OVERFLOW TRUNCATE and I implemented that into my SQL but now it generates missing right parenthesis error and I can't seem to figure out why? My query SELECT DISTINCT cust_id, acct_no, state, language_indicator, billing_system, market_code, EMAIL_ADDR, DATE_OF_CHANGE, TO_CHAR(DATE_LOADED, 'DD-MM-YYYY') DATE_LOADED, (SELECT LISTAGG( SUBSTR(mtn, 7, 4),'<br>' ON OVERFLOW TRUNCATE '***' ) WITHIN GROUP (ORDER BY cust_id || acct_no) mtnlist FROM process.feature WHERE date_loaded BETWEEN TO_DATE('02-08-2018','MM-dd-yyyy') AND TO_DATE('02-09-2018', 'MM-dd-yyyy') AND cust_id = ffsr.cust_id AND acct_no = ffsr.acct_no AND filename = 'FEATURE.VB2B.201802090040' GROUP BY cust_id||acct_no) mtnlist FROM process.feature ffsr WHERE date_loaded BETWEEN TO_DATE('02-08-2018','MM-dd-yyyy') AND TO_DATE('02-09-2018','MM-dd-yyyy') AND cust_id BETWEEN 0542185146 AND 0942025571 AND src_ind = 'B' AND filename = 'FEATURE.VB2B.201802090040' AND letter_type = 'FA' ORDER BY cust_id;
With a little bit of help by XML, you might get it work. Example is based on HR schema. SQL> select 2 listagg(s.department_name, ',') within group (order by null) result 3 from departments s, departments d; from departments s, departments d * ERROR at line 3: ORA-01489: result of string concatenation is too long SQL> SQL> select 2 rtrim(xmlagg(xmlelement (e, s.department_name || ',')).extract 3 ('//text()').getclobval(), ',') result 4 from departments s, departments d; RESULT -------------------------------------------------------------------------------- Administration,Administration,Administration,Administration,Administration,Admin SQL>
This demo sourced from livesql.oracle.com -- Create table with 93 strings of different lengths, plus one NULL string. Notice the only ASCII character not used is '!', so I will use it as a delimiter in LISTAGG. create table strings as with letters as ( select level num, chr(ascii('!')+level) let from dual connect by level <= 126 - ascii('!') union all select 1, null from dual ) select rpad(let,num,let) str from letters; -- Note the use of LENGTHB to get the length in bytes, not characters. select str, sum(lengthb(str)+1) over(order by str rows unbounded preceding) - 1 cumul_lengthb, sum(lengthb(str)+1) over() - 1 total_lengthb, count(*) over() num_values from strings where str is not null; -- This statement implements the ON OVERFLOW TRUNCATE WITH COUNT option of LISTAGG in 12.2. If there is no overflow, the result is the same as a normal LISTAGG. select listagg(str, '!') within group(order by str) || case when max(total_lengthb) > 4000 then '! ... (' || (max(num_values) - count(*)) || ')' end str_list from ( select str, sum(lengthb(str)+1) over(order by str) - 1 cumul_lengthb, sum(lengthb(str)+1) over() - 1 total_lengthb, count(*) over() num_values from strings where str is not null ) where total_lengthb <= 4000 or cumul_lengthb <= 4000 - length('! ... (' || num_values || ')');
How can I SELECT the row with max value?
select NATIONALPLAYERS.FIRSTNAME||' '|| NATIONALPLAYERS.LASTNAME as PlayerName, NATIONALPLAYERS.EXPERIENCEID, experience from NATIONALPLAYERS INNER JOIN (select experienceid, MAX( experiences.nationalgames + experiences.internationalgames ) as experience from experiences group by experiences.EXPERIENCEID)plexperience on plexperience.experienceid = NATIONALPLAYERS.experienceid; This displays all the records from PlayerName, ExperienceID, and Experience even though I asked only for the maximum value of experience.
What you are missing is the max experience. You are checking the experience_id but not making sure that the experience value is the max value The query should be something like: SELECT NATIONALPLAYERS.FIRSTNAME||' '|| NATIONALPLAYERS.LASTNAME as PlayerName, NATIONALPLAYERS.EXPERIENCEID, experience from NATIONALPLAYERS INNER JOIN ( select experienceid, MAX( experiences.nationalgames + experiences.internationalgames ) as experience from experiences group by experiences.EXPERIENCEID) AS plexperience on plexperience.experienceid = NATIONALPLAYERS.experienceid **plexperience.experience = NATIONALPLAYERS.experience;**
You are grouping by EXPERIENCEID and getting the maximum EXPERIENCE for each of those - you are not finding the EXPERIENCEID which corresponds to the maximum EXPERIENCE. If you want to find the values for the maximum experience then you want something like: SELECT * FROM ( select n.FIRSTNAME ||' '|| n.LASTNAME as PlayerName n.experienceid, e.nationalgames + e.internationgames as Experience from NATIONALPLAYERS n INNER JOIN EXPERIENCE e ON ( e.experienceid = n.experienceid ) ORDER BY Experience DESC ) WHERE ROWNUM = 1; or, if there are multiple highest rows: SELECT * FROM ( select n.FIRSTNAME ||' '|| n.LASTNAME as PlayerName n.experienceid, e.nationalgames + e.internationgames as Experience, RANK() OVER ( ORDER BY e.nationalgames + e.internationgames DESC ) AS rn from NATIONALPLAYERS n INNER JOIN EXPERIENCE e ON ( e.experienceid = n.experienceid ) ORDER BY Experience DESC ) WHERE rn = 1;