Related
I created a table like below. I want to select only NOT NULL column dynamically like(NO, NAME,SAL_1). No need to select SAL,SAL_2.
Note: Initially I don't know the columns values.
create table sample(no integer,name varchar(20),sal integer,sal_1 integer,sal_2 integer);
insert into sample(name,sal_1) values('aaa',10);
insert into sample(no,name,sal_1) values(20,'',20);
insert into sample(sal_1) values(30);
select * from sample;
data like below
NO NAME SAL SAL_1 SAL_2
20 (null) (null) 20 (null)
(null) (null) (null) 30 (null)
(null) aaa (null) 10 (null)
Expected op:
NO NAME SAL_1
20 (null) 20
(null) (null) 30
(null) aaa 10
The following query generates the query you want to execute through some dynamic SQL procedure.
Unfortunately I don't know well the Oracle syntax, the following is in PostgreSQL, but I guess you'll only have to change string_agg with the pertinent Oracle function catenating strings.
WITH columns (c) AS (
SELECT 'no' WHERE EXISTS (SELECT * FROM sample WHERE no IS NOT NULL)
UNION
SELECT 'name' WHERE EXISTS (SELECT * FROM sample WHERE name IS NOT NULL)
UNION
SELECT 'sal' WHERE EXISTS (SELECT * FROM sample WHERE sal IS NOT NULL)
UNION
SELECT 'sal_1' WHERE EXISTS (SELECT * FROM sample WHERE sal_1 IS NOT NULL)
UNION
SELECT 'sal_2' WHERE EXISTS (SELECT * FROM sample WHERE sal_2 IS NOT NULL)
)
SELECT 'SELECT ' || string_agg(c, ', ') || ' FROM sample;' FROM columns;
Try This,
I have checked and exactly match your output.
select no,"NAME",sal_1 from sample having count(sal_1)>0 group by
sal_1,name,no order by name desc
Try This,
select * from sample where nvl(NO,0)> 0 and nvl(length(NAME),0)>0 and nvl(SAL_1,0)>0
Table Columns: Id, Name, Age
First Rows:
select 11, 'James', 22 from dual;
This will return
11 James 22
Second Row:
select * from supplier where id=11`;
This will return
11 Vinod 25
Now I wanted to compare both rows:
11 James 22
11 Vinod 25
It should return the columns which has differences.
Name Mismatch
Age Mismatch
I am using 12c is there Built in feature in oracle which will solve this.
Or any other ways from which I can achieve the solution for the same.
Thanks In advance..
`
You can use join and decode (can use case alternatively) to find out if column value matches:
with cte(id, name, age) as (select 11, 'James', 22 from dual)
select
s.id,
decode(s.name, t.name, null, 'Name mismatch') name_check,
decode(s.age, t.age, null, 'Age mismatch') age_check
from supplier s
inner join cte t
on s.id = t.id
where s.id = 11;
I have a table p
id_people age
1 22
2 ---> (empty)
3 (10,20)
I want to get result like this
id_people age
1 22
3 10
3 20
I have tried this
select t.id_people,
STRTOK(t.age,',',1) AS COL_1,STRTOK(t.age,',',2) AS COL_2 from
(select id_people,age from p where LENGTH(age) >0 ) t
First of all , it works but i still have the brackets. how can i delete brackets ? Second question : It works fine because i know i have only one comma in a row, if i didn't know the number of comma in a row for column age, i wouldn't be able to handle by this way.
How can I use a kind of loop for a situation like that?
Example :
id_people age
1 (17,18,19,20,21,22,23,24,25,....)
2 (30,31,32)
3 --> (empty)
Thank you
Besides STRTOK there's also STRTOK_SPLIT_TO_TABLE :-)
The syntax is a bit unusual:
WITH cte (id_people, age) AS
(
SELECT id_people, age FROM dropme
)
SELECT *
FROM TABLE
( STRTOK_SPLIT_TO_TABLE( cte.id_people , cte.age, '(),')
RETURNS ( id_people INT , TokenNum INT , Token VARCHAR (10) CHARACTER SET UNICODE )
) dt
I am referring to this stackoverflow answer:
How can I select from list of values in SQL Server
How could something similar be done in Oracle?
I've seen the other answers on this page that use UNION and although this method technically works, it's not what I would like to use in my case.
So I would like to stay with syntax that more or less looks like a comma-separated list of values.
UPDATE regarding the create type table answer:
I have a table:
CREATE TABLE BOOK
( "BOOK_ID" NUMBER(38,0)
)
I use this script but it does not insert any rows to the BOOK table:
create type number_tab is table of number;
INSERT INTO BOOK (
BOOK_ID
)
SELECT A.NOTEBOOK_ID FROM
(select column_value AS NOTEBOOK_ID from table (number_tab(1,2,3,4,5,6))) A
;
Script output:
TYPE number_tab compiled
Warning: execution completed with warning
But if I use this script it does insert new rows to the BOOK table:
INSERT INTO BOOK (
BOOK_ID
)
SELECT A.NOTEBOOK_ID FROM
(SELECT (LEVEL-1)+1 AS NOTEBOOK_ID FROM DUAL CONNECT BY LEVEL<=6) A
;
You don't need to create any stored types, you can evaluate Oracle's built-in collection types.
select distinct column_value from table(sys.odcinumberlist(1,1,2,3,3,4,4,5))
If you are seeking to convert a comma delimited list of values:
select column_value
from table(sys.dbms_debug_vc2coll('One', 'Two', 'Three', 'Four'));
-- Or
select column_value
from table(sys.dbms_debug_vc2coll(1,2,3,4));
If you wish to convert a string of comma delimited values then I would recommend Justin Cave's regular expression SQL solution.
Starting from Oracle 12.2, you don't need the TABLE function, you can directly select from the built-in collection.
SQL> select * FROM sys.odcinumberlist(5,2,6,3,78);
COLUMN_VALUE
------------
5
2
6
3
78
SQL> select * FROM sys.odcivarchar2list('A','B','C','D');
COLUMN_VALUE
------------
A
B
C
D
There are various ways to take a comma-separated list and parse it into multiple rows of data. In SQL
SQL> ed
Wrote file afiedt.buf
1 with x as (
2 select '1,2,3,a,b,c,d' str from dual
3 )
4 select regexp_substr(str,'[^,]+',1,level) element
5 from x
6* connect by level <= length(regexp_replace(str,'[^,]+')) + 1
SQL> /
ELEMENT
----------------------------------------------------
1
2
3
a
b
c
d
7 rows selected.
Or in PL/SQL
SQL> create type str_tbl is table of varchar2(100);
2 /
Type created.
SQL> create or replace function parse_list( p_list in varchar2 )
2 return str_tbl
3 pipelined
4 is
5 begin
6 for x in (select regexp_substr( p_list, '[^,]', 1, level ) element
7 from dual
8 connect by level <= length( regexp_replace( p_list, '[^,]+')) + 1)
9 loop
10 pipe row( x.element );
11 end loop
12 return;
13 end;
14
15 /
Function created.
SQL> select *
2 from table( parse_list( 'a,b,c,1,2,3,d,e,foo' ));
COLUMN_VALUE
--------------------------------------------------------------------------------
a
b
c
1
2
3
d
e
f
9 rows selected.
You can do this:
create type number_tab is table of number;
select * from table (number_tab(1,2,3,4,5,6));
The column is given the name COLUMN_VALUE by Oracle, so this works too:
select column_value from table (number_tab(1,2,3,4,5,6));
Hi it is also possible for Strings with XML-Table
SELECT trim(COLUMN_VALUE) str FROM xmltable(('"'||REPLACE('a1, b2, a2, c1', ',', '","')||'"'));
[Deprecated] - Just to add for the op,
The issue with your second code it seems to be that you haven't defined there your "number_tab" type.
AS :
CREATE type number_tab is table of number;
SELECT a.notebook_id FROM (
SELECT column_value AS notebook_id FROM table (number_tab(1,2,3,4,5,6) ) ) a;
INSERT INTO BOOK ( BOOK_ID )
SELECT a.notebook_id FROM (
SELECT column_value AS notebook_id FROM table (number_tab(1,2,3,4,5,6) ) ) a;
DROP type number_tab ;
Sorry, I couldn't reproduce your error, could you send us the version of oracle used and the same code used for the procedure in the first instance?, that could help. All the best.
Is there any way to select the numbers (integers) that are included between two numbers with SQL in Oracle; I don't want to create PL/SQL procedure or function.
For example I need to get the numbers between 3 and 10. The result will be the values 3,4,5,6,7,8,9,10.
Thx.
This trick with Oracle's DUAL table also works:
SQL> select n from
2 ( select rownum n from dual connect by level <= 10)
3 where n >= 3;
N
----------
3
4
5
6
7
8
9
10
The first thing I do when I create a new database is to create and populate some basic tables.
One is a list of all integers between -N and N, another is a list of dates 5 years in the past through 10 years in the future (a scheduled job can continue creating these as needed, going forward) and the last is a list of all hours throughout the day. For example, the inetgers:
create table numbers (n integer primary key);
insert into numbers values (0);
insert into numbers select n+1 from numbers; commit;
insert into numbers select n+2 from numbers; commit;
insert into numbers select n+4 from numbers; commit;
insert into numbers select n+8 from numbers; commit;
insert into numbers select n+16 from numbers; commit;
insert into numbers select n+32 from numbers; commit;
insert into numbers select n+64 from numbers; commit;
insert into numbers select n+128 from numbers; commit;
insert into numbers select n+256 from numbers; commit;
insert into numbers select n+512 from numbers; commit;
insert into numbers select n+1024 from numbers; commit;
insert into numbers select n+2048 from numbers; commit;
insert into numbers select n+4096 from numbers; commit;
insert into numbers select n+8192 from numbers; commit;
insert into numbers select -n from numbers where n > 0; commit;
This is for DB2/z which has automatic transaction start which is why it seems to have naked commits.
Yes, it takes up a (minimal) space but it makes queries much easier to write, simply by selecting values from those tables. It's also very portable across pretty much any SQL-based DBMS.
Your particular query would then be a simple:
select n from numbers where n >=3 and n <= 10;
The hour figures and date ranges are quite useful for the sort of reporting applications we work on. It allows us to create zero entries for those hours of the day (or dates) which don't have any real data so that, instead of (where there's no data on the second of the month):
Date | Quantity
-----------+---------
2009-01-01 | 7
2009-01-03 | 27
2009-01-04 | 6
we can instead get:
Date | Quantity
-----------+---------
2009-01-01 | 7
2009-01-02 | 0
2009-01-03 | 27
2009-01-04 | 6
SQL> var N_BEGIN number
SQL> var N_END number
SQL> exec :N_BEGIN := 3; :N_END := 10
PL/SQL procedure successfully completed.
SQL> select :N_BEGIN + level - 1 n
2 from dual
3 connect by level <= :N_END - :N_BEGIN + 1
4 /
N
----------
3
4
5
6
7
8
9
10
8 rows selected.
This uses the same trick as Tony's. Note that when you are using SQL*Plus 9, you have to make this query an inline view as Tony showed you. In SQL*Plus 10 or higher, the above is sufficient.
Regards,
Rob.
You can use the MODEL clause for this.
SELECT c1 from dual
MODEL DIMENSION BY (1 as rn) MEASURES (1 as c1)
RULES ITERATE (7)
(c1[ITERATION_NUMBER]=ITERATION_NUMBER+7)
this single line query will help you,
select level lvl from dual where level<:upperbound and
level >:lowerbound connect by level<:limt
For your case:
select level lvl from dual where level<10 and level >3 connect by level<11
let me know if any clarification.
One way to generate numbers from range is to use XMLTABLE('start to end'):
SELECT TO_NUMBER(column_value) integer_value
FROM XMLTABLE('3 to 10');
I added TO_NUMBER because COLUMN_VALUE is a string
DBFiddle Demo
Or you can use Between
Select Column1 from dummy_table where Column2 Between 3 and 10
Gary, to show the result that he explained, the model query will be:
SELECT c1
FROM DUAL
MODEL DIMENSION BY (1 as rn)
MEASURES (1 as c1)
RULES ITERATE (8)
(c1[ITERATION_NUMBER]=ITERATION_NUMBER+3)
ORDER BY rn
;)
I always use:
SELECT (LEVEL - 1) + 3 as result
FROM Dual
CONNECT BY Level <= 8
Where 3 is the start number and 8 is the number of "iterations".
This is a late addition. But the solution seems to be more elegant and easier to use.
It uses a pipelined function that has to be installed once:
CREATE TYPE number_row_type AS OBJECT
(
num NUMBER
);
CREATE TYPE number_set_type AS TABLE OF number_row_type;
CREATE OR REPLACE FUNCTION number_range(p_start IN PLS_INTEGER, p_end IN PLS_INTEGER)
RETURN number_set_type
PIPELINED
IS
out_rec number_row_type := number_row_type(NULL);
BEGIN
FOR i IN p_start .. p_end LOOP
out_rec.num := i;
pipe row(out_rec);
END LOOP;
END number_range;
/
Then you can use it like this:
select * from table(number_range(1, 10));
NUM
---
1
2
3
4
5
6
7
8
9
10
The solution is Oracle specific.
I just did a table valued function to do this in SQL server, if anyone is interested, this works flawlessly.
CREATE FUNCTION [dbo].[NumbersBetween]
(
#StartN int,
#EndN int
)
RETURNS
#NumberList table
(
Number int
)
AS
BEGIN
WHILE #StartN <= #EndN
BEGIN
insert into #NumberList
VALUES (#StartN)
set #StartN = #StartN + 1
END
Return
END
GO
If you run the query: "select * from dbo.NumbersBetween(1,5)" (w/o the quotes of course) the result will be
Number
-------
1
2
3
4
5
I want to share an usefull query that converts a string of comma and '-' separated list of numbers into a the equivalent expanded list of numbers:
An example that converts '1,2,3,50-60' into
1
2
3
50
51
...
60
select distinct * from (SELECT (LEVEL - 1) + mini as result FROM (select REGEXP_SUBSTR (value, '[^-]+', 1, 1)mini ,nvl(REGEXP_SUBSTR (value, '[^-]+', 1, 2),0) maxi from (select REGEXP_SUBSTR (value, '[^,]+', 1, level) as value from (select '1,2,3,50-60' value from dual) connect by level <= length(regexp_replace(value,'[^,]*'))+1)) CONNECT BY Level <= (maxi-mini+1)) order by 1 asc;
You may use it as a view and parametrize the '1,2,3,50-60' string
create table numbers (value number);
declare
x number;
begin
for x in 7 .. 25
loop
insert into numbers values (x);
end loop;
end;
/
In addition to the answers already provided, it is possible to combine the listagg function with connect by to obtain the result in the format mentioned in the question. See a code example below:
SELECT
DBMS_LOB.SUBSTR(LISTAGG(S.INTEGERS,',' ) WITHIN GROUP (ORDER BY S.INTEGERS), 300,1) RESULT
FROM
(SELECT
INTEGERS
FROM
( SELECT ROWNUM INTEGERS FROM DUAL CONNECT BY LEVEL <= 10)
WHERE
INTEGERS >= 3
) S;
OutPut:
SQL>
RESULT
----------------
3,4,5,6,7,8,9,10