Recursive SQL retrieve all levels - sql

I am unable to retrieve the desired result my query when using Oracle's recursive approach:
Foo
ID1 ID2
1 2
1 3
4 2
4 3
4 5
Query:
select sys_connect_by_path(id2,' -> ')
FROM Foo
START WITH id1 = 1
CONNECT BY PRIOR id1 = id2
ORDER BY 1;
Outputs only level 1 hierarchy (2,3). I want it to detect the tree ( 1 -> (2,3) -> 4 -> 5 ), such that selecting distinct ID2 yields (2,3,5). Thank you.

If you are using Oracle 11.2 or above, a CTE (Common Table Expression) is preferred over using Oracle's CONNECT BY statement.
WITH
aset -- Create pseudo table with ID2 as ID1 and vice versa
AS
(SELECT id1, id2
FROM (SELECT id1, id2
FROM foo
UNION
SELECT id2, id1
FROM foo)
WHERE id1 < id2),
bset (id1, id2) -- Extract hierarchy from pseudo table
AS
(SELECT id1, id2
FROM aset
WHERE id1 = 1
UNION ALL
SELECT aset.id1, aset.id2
FROM bset INNER JOIN aset ON bset.id2 = aset.id1
WHERE bset.id1 <> aset.id2)
SELECT DISTINCT bset.id2 -- Only keep values that were originally ID2
FROM bset INNER JOIN foo ON bset.id2 = foo.id2
ORDER BY id2;
Here is the same thing using CONNECT BY
WITH
aset
-- Create pseudo table with ID2 as ID1 and vice versa
AS
(SELECT id1, id2
FROM (SELECT id1, id2
FROM foo
UNION
SELECT id2, id1
FROM foo)
WHERE id1 < id2),
bset
-- Extract hierarchy from pseudo table
AS
( SELECT id2
FROM aset
START WITH id1 = 1
CONNECT BY PRIOR id2 = id1)
SELECT DISTINCT bset.id2
-- Only keep values that were originally ID2
FROM bset INNER JOIN foo ON bset.id2 = foo.id2
ORDER BY id2

Related

"duplicate" rows - how to select distinct

I have a table with this structure
id1 id2
--------------
10 2
2 10
12 15
I need to select "distinct" using SQL in the sense that rows 1 and 2 are considered the same
So I need a query that results in
10 2
12 15
or
2 10
12 15
Both are fine.
Any good ideas. This problem is driving me crazy :-)
One simple method is:
select t.*
from t
where a < b or
not exists (select 1 from t t2 where t2.b = t.a and t2.a = t.b)
In a DBMS that supports LEAST and GREATEST you can use these to get ordered pairs:
select distinct
least(id1, id2) as lesser_id,
greatest(id1, id2) as greater_id
from mytable;
In a DBMS that doesn't support these functions , you can use CASE expressions to achieve the same:
select distinct
case when id1 <= id2 then id1 else id2 as lesser_id,
case when id1 >= id2 then id1 else id2 as greater_id
from mytable;
I would do:
SELECT DISTINCT id1, id2
FROM (
SELECT id1, id2 FROM mytable
UNION
SELECT id2, id1 FROM mytable
) AS combinations
Another solution, using relations instead of a DISTINCT clause:
SELECT A.id1, A.id2
FROM mytable A LEFT JOIN mytable B ON A.id1 > B.id1 AND A.id1 = B.id2 AND A.id2 = B.id1
WHERE B.id1 IS NULL

how to get unique data from multiple columns in db2

I wanted to get data from 2 columns in below way:
Id1 id2 id3
1 1 2
2 3 null
2 4 null
O/p
Id1 data
1 1,2
2 3,4
Here id1 is pk and id2 and id3 is fk of other table.
Try this as is:
WITH TAB (ID1, ID2, ID3) AS
(
VALUES
(1, 1, 2)
, (2, 3, NULL)
, (2, 4, NULL)
)
SELECT ID1, LISTAGG(DISTINCT ID23, ',') AS DATA
FROM
(
SELECT T.ID1, CASE V.ID WHEN 2 THEN T.ID2 ELSE T.ID3 END AS ID23
FROM TAB T
CROSS JOIN (VALUES 2, 3) V(ID)
)
WHERE ID23 IS NOT NULL
GROUP BY ID1;
This is a bit strange -- concatenating both within the same row and across multiple rows. One method is to unpivot and then aggregate:
select id1, listagg(id2, ',') within group (order by id2)
from (select id1, id2 from t union all
select id1, id3 from t
) t
where id2 is not null
group by id1;
Assuming that only id2 could be NULL, you can also express this as:
select id1,
listagg(concat(id2, coalesce(concat(',', id3), '')), ',') within group (order by id2)
from t
group by id1;

Select a subcategory ID to associate with a primary ID based off which has the highest sum

I have a primary ID, ID1, and a secondary ID, ID2. ID1 can be associated with multiple ID2 values, and vice versa. I want to sum a third Values column by ID2 under each ID1, and pull the ID2 with the highest sum. The source data is structured like:
ID1 ID2 Value
1 10 1
1 10 2
1 20 1
2 10 1
2 30 2
And I want the final results to look like:
ID1 ID2
1 10
2 30
So far, I only have a nonfunctioning query:
SELECT ID1,
CASE WHEN ID2_Value = MAX(ID2_Value) THEN ID2
ELSE NULL
END AS PrimaryID2
FROM ( SELECT ID1,
ID2,
SUM(Value) AS ID2_Value
FROM SOME_SCHEMA
GROUP BY ID1, ID2
) AS ID2_Value
GROUP BY ID1;
My query doesn't work right now because it expects me to include ID2_Value in the GROUP BY statement, but I don't want to group by those values.
I would use row_number():
select id1, id2
from (select id1, id2, sum(value) as sumv,
row_number() over (partition by id1 order by sum(value) desc) as seqnum
from t
group by id1, id2
) t
where seqnum = 1;

Oracle 11.2 SQL - help to condense data in ordered set

I have a data-set with a timestamp column and multiple identifier columns. I want to condense it to a single row for each "block" of adjacent rows with equal identifiers, when ordered by the timestamp. The min and max timestamp for each block is required.
Source Data:
TSTAMP ID1 ID2
t1 A B <= start of new block
t2 A B
t3 C D <= start of new block
t4 E F <= start of new block
t5 E F
t6 E F
t7 A B <= start of new block
t8 G H <= start of new block
Desired Result:
MIN_TSTAMP MAX_TSTAMP ID1 ID2
t1 t2 A B
t3 t3 C D
t4 t6 E F
t7 t7 A B
t8 t8 G H
I thought this was ripe for a window-ing analytic function but I cannot partition without grouping ALL equal combinations of IDn - rather than only those in adjacent rows, when ordered by timestamp.
A workaround is to create a key column first in an in-line view that I can later group by i.e. with same value for each row in the block and different value for each block. I can do this using LAG analytic function to compare row values and then calling a PL/SQL function to return nextval/currval values of a sequence (calling nextval/currval directly in the SQL is restricted in this context).
select min(ilv.tstamp), max(ilv.tstamp), id1, id2
from (
select case when (id1 != lag(id1,1,'*') over (partition by (1) order by tstamp)
or id2 != lag(id2,1,'*') over (partition by (1) order by tstamp))
then
pk_seq_utils.gav_get_nextval
else
pk_seq_utils.gav_get_currval
end ident, t.*
from tab1 t
order by tstamp) ilv
group by ident, id1, id2
order by 1;
where the gav_get_xxx functions simply return currval/nextval from a sequence.
But I would like to use SQL only and avoid PL/SQL (as I could also write this easily in PL/SQL and pipe out the result-rows from a pipeline function).
Any ideas?
Thanks.
Tabibitosan to the rescue!
with sample_data as (select 't1' tstamp, 'A' id1, 'B' id2 from dual union all
select 't2' tstamp, 'A' id1, 'B' id2 from dual union all
select 't3' tstamp, 'C' id1, 'D' id2 from dual union all
select 't4' tstamp, 'E' id1, 'F' id2 from dual union all
select 't5' tstamp, 'E' id1, 'F' id2 from dual union all
select 't6' tstamp, 'E' id1, 'F' id2 from dual union all
select 't7' tstamp, 'A' id1, 'B' id2 from dual union all
select 't8' tstamp, 'G' id1, 'H' id2 from dual)
select min(tstamp) min_tstamp, max(tstamp) max_tstamp, id1, id2
from (select tstamp,
id1,
id2,
row_number() over (order by tstamp) - row_number() over (partition by id1, id2 order by tstamp) grp
from sample_data)
group by id1,
id2,
grp
order by min(tstamp);
MIN_TSTAMP MAX_TSTAMP ID1 ID2
---------- ---------- --- ---
t1 t2 A B
t3 t3 C D
t4 t6 E F
t7 t7 A B
t8 t8 G H
You can use an analytic 'trick' to identify the gaps and islands, comparing the position of each row just against the tstamp across all rows with its position against tstamp just for that id2, id2 combination:
select tstamp, id1, id2,
row_number() over (partition by id1, id2 order by tstamp)
- row_number() over (order by tstamp) as block_id
from tab1;
TS I I BLOCK_ID
-- - - ----------
t1 A B 0
t2 A B 0
t3 C D -2
t4 E F -3
t5 E F -3
t6 E F -3
t7 A B -4
t8 G H -7
The actual value of block_id doesn't matter, just that it's unique for each block for the combination. You can then group using that:
select min(tstamp) as min_tstamp, max(tstamp) as max_tstamp, id1, id2
from (
select tstamp, id1, id2,
row_number() over (partition by id1, id2 order by tstamp)
- row_number() over (order by tstamp) as block_id
from tab1
)
group by id1, id2, block_id
order by min(tstamp);
MI MA I I
-- -- - -
t1 t2 A B
t3 t3 C D
t4 t6 E F
t7 t7 A B
t8 t8 G H
You should be able to use the row_number window function to do this, like below:
select
min(tstamp) mints, max(tstamp) maxts, id1, id2
from (
select
*,
row_number() over (order by tstamp)
- row_number() over (partition by id1, id2 order by tstamp) as rn
from t
) as subq
group by id1, id2, rn
order by rn
I haven't been able to test it with any Oracle db, but it works with MSSQL and should work in Oracle too as the window function works the same way.
You need to do this step by step:
Detect ID changes with LAG marking each change with a flag = 1.
Generate keys for the groups (i.e. adjacent records with the same ID) with SUM over the ID change flags (running total).
Group by generated group key and get min/max timestamp.
Query:
select
min(tstamp) as min_tstamp,
max(tstamp) as max_tstamp,
min(id1) as id1,
min(id2) as id2
from
(
select
grouped.*,
sum(newgroup) over (order by tstamp) as groupkey
from
(
select
mytable.*,
case when id1 <> lag(id1) over (order by tstamp)
or id2 <> lag(id2) over (order by tstamp)
then 1 else 0 end as newgroup
from mytable
order by tstamp
) grouped
)
group by groupkey
order by groupkey;

Getting values from column B that do not have a corresponding value in column A

I have a table with two columns in MSSQL.
column id1 and column id2 with any relation .
Example data:
id1 id2
12 13
13 14
12 14
13 15
Here 12 in id1 is has relation with 13 in id2,
here 13 in id1 is has relation with 14 in id2
such way..
How can I write an SQL Query so that when I pass 12, I get the value(s) from column id2 who does not have any relation with 12?
(In this case, the answer would be 15)
You can use a subquery in the where clause.
SELECT id2 FROM `test1`
WHERE id2 NOT IN (SELECT id2 FROM `test1` WHERE id1 = 12)
If you any NULLs in id2, then NOT IN will always fail
You have to use EXISTS or EXCEPT for consistency and correct results
SELECT tr.id2
FROM MyTable tr
WHERE NOT EXISTS (SELECT * FROM MyTable tl
WHERE tl.id1 = 12 AND tl.id2 = tr.id2)
Or
SELECT id2
FROM MyTable
EXCEPT
SELECT id2
FROM MyTable
WHERE id1 = 12
I think it's as simple as:
select distinct id2
from table
where id2 not in (select id2 from table where id1 = 12)
I.e. you want to find all id2 values, such that no row with that id2 value has an id1 of 12