working with permutations of a column values - sql

I am trying from the below table
key val
A 10
B 20
C 30
D 40
to achieve the following result. Column label displays all combinations of key in alphabetical order. Column total displays the addition of the vals for the combination of keys.
label total
A 10
AB 30
ABC 60
ABCD 100
AC 40
AD 50
B 20
BC 50
BCD 90
BD 60
C 30
CD 70
D 40
while managed to get a query going, still not so convinced with it. Looking for better ways to get the same result set. thanks in advance.
with f (rn, key, val) as
(
select rownum, a.* from
(
select 'A' key, 10 val from dual
union all select 'B', 20 from dual
union all select 'C', 30 from dual
union all select 'D', 40 from dual
-- union all select 'E', 50 from dual
-- union all select 'F', 60 from dual
order by 1
) a
)
,
-- irn, ikey, ival: anchor rownum, key and val to remember the starting row
-- rn, key, val: for the current row in the recursion
-- r1: current label in the recursion
-- r2: combination of anchor key and the current row key in the recursion
-- total: addition of all values for keys in r1
rs(irn, ikey, ival, rn, key, val, r1, r2, total) as
(
select rn, key, val, rn, key, val, key, null, val from f
union all
select rs.irn, rs.ikey, rs.ival, f.rn, f.key, f.val, rs.r1 || f.key, rs.ikey || f.key, rs.total+f.val
from rs join f on (f.rn = rs.rn+1)
)
,
-- to add the additional rows required for the r2 col
-- when either r2 is not empty and not the same as r1 in rs
frs(irn, ikey, ival, rn, key, val, r1, r2, total) as
(
select * from rs
union all
select irn, ikey, ival, rn, key, val, r2, r2, ival+val
from frs
where r2 is not null and r1 != r2
)
select r1, total from frs
order by 1
;

Here is one way - using recursive subquery factoring, available since Oracle 11.2:
with
-- Begin test data
test_data ( key, val ) as (
select 'A', 10 from dual union all
select 'B', 20 from dual union all
select 'C', 30 from dual union all
select 'D', 40 from dual
),
-- End of test data (not part of the solution).
-- SQL query begins with the keyword "with" from above and continues below this line.
rec_cte ( label, total, last_symbol ) as (
select key, val, key -- anchor member
from test_data
union all
select r.label || t.key, r.total + t.val, t.key -- recursive member
from rec_cte r join test_data t on r.last_symbol < t.key
)
select label, total
from rec_cte
order by label -- if needed
;
Output:
LABEL TOTAL
----- -----
A 10
AB 30
ABC 60
ABCD 100
ABD 70
AC 40
ACD 80
AD 50
B 20
BC 50
BCD 90
BD 60
C 30
CD 70
D 40
15 rows selected.

You can use a PL/SQL block/Proceduere to achieve the same.
Assuming t_perm is your table, this proc will give you what you want. But currently it is displaying it on dbms_output. You can insert it in a table or display by a cursor etc. But this is the logic
create or replace procedure perm as
v_hold varchar2(20);
v_sum integer:=0;
cursor crs is select * from t_perm;
cursor crs1 is select * from t_perm;
begin
for rec in crs
loop
for rec1 in crs1
loop
if rec.key <= rec1.key then
v_hold:=v_hold||rec1.key;
v_sum:=v_sum+rec1.val;
dbms_output.put_line(v_hold||' '||v_sum);
end if;
end loop;
v_hold:='';
v_sum:=0;
end loop;
end;
Output
A 10
AB 30
ABC 60
ABCD 100
B 20
BC 50
BCD 90
C 30
CD 70
D 40

Related

Deleting duplicates on combination of two columns in oracle

I have a table for example :
Port Table
S No
A Port
B port
1
80
100
2
90
110
3
100
80
4
94
106
I want to delete record no. 3 as it is having same combination as record no. 1 how to do this in oracle ?
You can use a single MERGE statement and the ROW_NUMBER analytic function combined with GREATEST and LEAST to find and delete the duplicates:
MERGE INTO table_name dst
USING (
SELECT ROWID rid,
ROW_NUMBER() OVER (
PARTITION BY LEAST(A_Port, B_Port), GREATEST(A_Port, B_Port)
ORDER BY S_no
) AS rn
FROM table_name
) src
ON (dst.ROWID = src.rid AND src.rn > 1)
WHEN MATCHED THEN
UPDATE SET A_port = NULL
DELETE WHERE 1 = 1;
Which, for your sample data:
CREATE TABLE table_name (S_No, A_Port, B_port) AS
SELECT 1, 80, 100 FROM DUAL UNION ALL
SELECT 2, 90, 110 FROM DUAL UNION ALL
SELECT 3, 100, 80 FROM DUAL UNION ALL
SELECT 4, 94, 106 FROM DUAL;
Will delete the 3rd row.
db<>fiddle here
Tried this in mysql, do some test/scenarios
SELECT P1.* FROM port_tbl AS P1
LEFT JOIN port_tbl AS P2 ON P1.port1 = P2.port2 OR P1.port2 = P2.port1
WHERE P1.id < P2.id OR ISNULL(P2.id)
ORDER BY P1.id;

Oracle SQL generate random output with listaggs

I have the values 30, 31, 32 and 33
How could I generate a output (random) which may contain single values of that list, listaggs of them or nulls?
id
val
1
30, 31
2
null
3
32
4
33
5
null
6
31, 33
7
null
8
30
Here is a way - generating the strings quasi-randomly (using ora_hash to do the trick), while in a perfectly deterministic, reproducible way. If you want to get different (but similar) results, use the third argument to ora_hash to provide a seed different from the default (which is 0). If you want different results every time, provide a dbms_random.value() value as the seed; this will still require just one "random" value to be generated for the entire query. You can also play with the upper bound (in my example, 280) to get more or fewer null (and shorter vs. longer comma-separated strings, more generally).
WITH data ( value ) AS (
SELECT 30 FROM DUAL UNION ALL
SELECT 31 FROM DUAL UNION ALL
SELECT 32 FROM DUAL UNION ALL
SELECT 33 FROM DUAL
),
ids ( id ) AS (
SELECT LEVEL
FROM DUAL
CONNECT BY LEVEL <= 8
)
select id,
( select listagg(case when ora_hash(id * value, 1000) < 280
then value end, ',')
within group(order by value)
from data
) as vals
from ids
;
ID VALS
-- ---------------
1 33
2 32
3
4 30,32
5 30,31
6 32
7
8
You can do it but you need to add some seemingly irrelevant filters to force the SQL optimiser to not materialize the sub-query and to ensure the values are randomly generated for each row:
WITH data ( value ) AS (
SELECT 30 FROM DUAL UNION ALL
SELECT 31 FROM DUAL UNION ALL
SELECT 32 FROM DUAL UNION ALL
SELECT 33 FROM DUAL
),
ids ( id ) AS (
SELECT LEVEL
FROM DUAL
CONNECT BY LEVEL <= 8
)
SELECT id,
(
SELECT LISTAGG( value, ',' ) WITHIN GROUP ( ORDER BY value )
FROM (
SELECT value,
DBMS_RANDOM.VALUE() AS rnd
FROM data
WHERE ROWNUM > 0 -- force a new random on each row.
)
WHERE rnd < 0.5
AND id > 0 -- force the query to correlate with the outer query.
) AS vals
FROM ids;
Which may output:
ID
VALS
1
33
2
30,31,32
3
31,32
4
<null>
5
30,32
6
31,33
7
30,31,32,33
8
30,31,32,33
db<>fiddle here

Oracle Finding a string match from multiple database tables

This is somewhat a complex problem to describe, but I'll try to explain it with an example. I thought I would have been able to use the Oracle Instr function to accomplish this, but it does not accept queries as parameters.
Here is a simplification of my data:
Table1
Person Qualities
Joe 5,6,7,8,9
Mary 7,8,10,15,20
Bob 7,8,9,10,11,12
Table2
Id Desc
5 Nice
6 Tall
7 Short
Table3
Id Desc
8 Angry
9 Sad
10 Fun
Table4
Id Desc
11 Boring
12 Happy
15 Cool
20 Mad
Here is somewhat of a query to give an idea of what I'm trying to accomplish:
select * from table1
where instr (Qualities, select Id from table2, 1,1) <> 0
and instr (Qualities, select Id from table3, 1,1) <> 0
and instr (Qualities, select Id from table3, 1,1) <> 0
I'm trying to figure out which people have at least 1 quality from each of the 3 groups of qualities (tables 2,3, and 4)
So Joe would not be returned in the results because he does not have the quality from each of the 3 groups, but Mary and Joe would since they have at least 1 quality from each group.
We are running Oracle 12, thanks!
Here's one option:
SQL> with
2 table1 (person, qualities) as
3 (select 'Joe', '5,6,7,8,9' from dual union all
4 select 'Mary', '7,8,10,15,20' from dual union all
5 select 'Bob', '7,8,9,10,11,12' from dual
6 ),
7 table2 (id, descr) as
8 (select 5, 'Nice' from dual union all
9 select 6, 'Tall' from dual union all
10 select 7, 'Short' from dual
11 ),
12 table3 (id, descr) as
13 (select 8, 'Angry' from dual union all
14 select 9, 'Sad' from dual union all
15 select 10, 'Fun' from dual
16 ),
17 table4 (id, descr) as
18 (select 11, 'Boring' from dual union all
19 select 12, 'Happy' from dual union all
20 select 15, 'Cool' from dual union all
21 select 20, 'Mad' from dual
22 ),
23 t1new (person, id) as
24 (select person, regexp_substr(qualities, '[^,]+', 1, column_value) id
25 from table1 cross join table(cast(multiset(select level from dual
26 connect by level <= regexp_count(qualities, ',') + 1
27 ) as sys.odcinumberlist))
28 )
29 select a.person,
30 count(b.id) bid,
31 count(c.id) cid,
32 count(d.id) did
33 from t1new a left join table2 b on a.id = b.id
34 left join table3 c on a.id = c.id
35 left join table4 d on a.id = d.id
36 group by a.person
37 having ( count(b.id) > 0
38 and count(c.id) > 0
39 and count(d.id) > 0
40 );
PERS BID CID DID
---- ---------- ---------- ----------
Bob 1 3 2
Mary 1 2 2
SQL>
What does it do?
lines #1 - 22 represent your sample data
T1NEW CTE (lines #23 - 28) splits comma-separated qualities into rows, per every person
final select (lines #29 - 40) are outer joining t1new with each of "description" tables (table2/3/4) and counting how many qualities are contained in there for each of person's qualities (represented by rows from t1new)
having clause is here to return only desired persons; each of those counts have to be a positive number
Maybe this will help:
{1} Create a view that categorises all qualities and allows you to SELECT quality IDs and categories . {2} JOIN the view to TABLE1 and use a join condition that "splits" the CSV value stored in TABLE1.
{1} View
create or replace view allqualities
as
select 1 as category, id as qid, descr from table2
union
select 2, id, descr from table3
union
select 3, id, descr from table4
;
select * from allqualities order by category, qid ;
CATEGORY QID DESCR
---------- ---------- ------
1 5 Nice
1 6 Tall
1 7 Short
2 8 Angry
2 9 Sad
2 10 Fun
3 11 Boring
3 12 Happy
3 15 Cool
3 20 Mad
{2} Query
-- JOIN CONDITION:
-- {1} add a comma at the start and at the end of T1.qualities
-- {2} remove all blanks (spaces) from T1.qualities
-- {3} use LIKE and the qid (of allqualities), wrapped in commas
--
-- inline view: use UNIQUE, otherwise we may get counts > 3
--
select person
from (
select unique person, category
from table1 T1
join allqualities A
on ',' || replace( T1.qualities, ' ', '' ) || ',' like '%,' || A.qid || ',%'
)
group by person
having count(*) = ( select count( distinct category ) from allqualities )
;
-- result
PERSON
Bob
Mary
Tested w/ Oracle 18c and 11g. DBfiddle here.

Oracle SQL running total on change of field (SUM on column only when field changes)

I have a question in regards to how to SUM on a column only when a field is changing.
Take for example the table below:
Note that Column A and Column B are different tables. I.e. A was selected from Table X and B was selected from Table Y
SELECT X.A, Y.B
FROM X
INNER JOIN Y ON X.DATE = Y.DATE AND X.VAL1 =
Y.VAL1 AND X.VAL2 = Y.VAL2
A B
123 5
123 5
456 10
789 15
789 15
I need to sum column B on change of field on column A:
I.e. the query should return 5 + 10 + 15 = 30 (5 the first time because value in column A is 123, 10 the second time because column A changed from 123 to 456 - note that the second row was skipped because column A still contains value 123 - hence the change of field logic and so on).
I can't do a simple SUM(B) because that would return 50. I also cannot do SUM(B) OVER (PARTITION BY A) because that would do a running total by group, not by change of field.
My output needs to look like this:
A B X
123 5 5
123 5 5
456 10 15
789 15 30
789 15 30
I am trying to do this within a simple query. Is there a particular function I can use to do this?
For the simple data set provided, the following should work. You will, of course, want to review the ORDER BY clauses for correctness in your exact use case.
SELECT a
,b
,SUM(CASE WHEN a = prev_a THEN 0 ELSE b END) OVER (ORDER BY a RANGE UNBOUNDED PRECEDING) AS x
FROM (
SELECT a
,b
,LAG(a) OVER (ORDER BY a) AS prev_a
FROM {your_query}
)
This solution makes use of the LAG function, which returns the specified column from the previous result. Then the outer query's SUM gives the value only when the previous row didn't have the same value. And there is also the windowing clause involved in the SUM because you specified that you needed a running total.
Ta-daaa?
SQL> with test (a, b) as
2 (select 123, 5 from dual union all
3 select 123, 5 from dual union all
4 select 456, 10 from dual union all
5 select 789, 15 from dual union all
6 select 789, 15 from dual
7 ),
8 proba as(
9 select a, b,
10 case when a <> nvl(lag(a) over (order by a), 0) then 'Y' else 'N' end switch
11 from test
12 )
13 select a, b,
14 sum(decode(switch, 'Y', b, 0)) over (partition by null order by a) x
15 from proba
16 order by a;
A B X
---------- ---------- ----------
123 5 5
123 5 5
456 10 15
789 15 30
789 15 30
SQL>
you can also create a function and use it, see sample below,
create package test_pkg123
as
a number;
r_sum NUMBER;
function get_r_sum(p_a number, p_val NUMBER, rown NUMBER) return number;
end;
/
create or replace package body test_pkg123
as
function get_r_sum(p_a number, p_val NUMBER, rown NUMBER) return number
is
begin
if rown = 1 then
r_sum := p_val;
return r_sum;
end if;
if p_a != a then
r_sum := nvl(r_sum, 0) + nvl(p_val, 0);
end if;
a := p_a;
return r_sum;
end;
end;
/
with test (a, b) as
(select 123, 5 from dual union all
select 123, 5 from dual union all
select 456, 10 from dual union all
select 789, 15 from dual union all
select 789, 15 from dual union all
select 789, 15 from dual union all
select 123, 2 from dual
)
select a, b, test_pkg123.get_r_sum(a, b, rownum) r_sum
from test;
Output:
A B R_SUM
123 5 5
123 5 5
456 10 15
789 15 30
789 15 30
789 15 30
123 2 32
7 rows selected

How can I find unoccupied id numbers in a table?

In my table I want to see a list of unoccupied id numbers in a certain range.
For example there are 10 records in my table with id's: "2,3,4,5,10,12,16,18,21,22" and say that I want to see available ones between 1 and 25. So I want to see a list like:
1,6,7,89,11,13,14,15,17,19,20,23,24,25
How should I write my sql query?
Select the numbers form 1 to 25 and show only those that are not in your table
select n from
( select rownum n from dual connect by level <= 25)
where n not in (select id from table);
Let's say you a #numbers table with three numbers -
CREATE TABLE #numbers (num INT)
INSERT INTO #numbers (num)
SELECT 1
UNION
SELECT 3
UNION
SELECT 6
Now, you can use CTE to generate numbers recursively from 1-25 and deselect those which are in your #numbers table in the WHERE clause -
;WITH n(n) AS
(
SELECT 1
UNION ALL
SELECT n+1 FROM n WHERE n < 25
)
SELECT n FROM n
WHERE n NOT IN (select num from #numbers)
ORDER BY n
OPTION (MAXRECURSION 25);
You can try using the "NOT IN" clause:
select
u1.user_id + 1 as start
from users as u1
left outer join users as u2 on u1.user_id + 1 = u2.id
where
u2.id is null
see also SQL query to find Missing sequence numbers
You need LISTAGG to get the output in a single row.
SQL> WITH DATA1 AS(
2 SELECT LEVEL rn FROM dual CONNECT BY LEVEL <=25
3 ),
4 data2 AS(
5 SELECT 2 num FROM dual UNION ALL
6 SELECT 3 FROM dual UNION ALL
7 SELECT 4 from dual union all
8 SELECT 5 FROM dual UNION ALL
9 SELECT 10 FROM dual UNION ALL
10 SELECT 12 from dual union all
11 SELECT 16 from dual union all
12 SELECT 18 FROM dual UNION ALL
13 SELECT 21 FROM dual UNION ALL
14 SELECT 22 FROM dual)
15 SELECT listagg(rn, ',')
16 WITHIN GROUP (ORDER BY rn) num_list FROM data1
17 WHERE rn NOT IN(SELECT num FROM data2)
18 /
NUM_LIST
----------------------------------------------------
1,6,7,8,9,11,13,14,15,17,19,20,23,24,25
SQL>