Filtering data by comparing tables - sql

I have two tables A & B. I want to extract column 1 from table A and make sure that I only extract data that does not exist in column 1 & 2 in table B. How can I achieve this?
Additionally, column 2 in table B contains aggregated data, which means that the data looks like[a,b,c,d].
Example:
Table A
column_1
a
b
c
d
e
Table B
column_1
column_2
a
[a,b,c,d]
z
[c,b,s,f]
x
[g,h,i,j]
y
[k,l,m,n]
z
[o,p,q,r]
In this example, I want to extract only 'e' from table A as it is not in either column_1 or column_2 from table B.

One way is to concatenate to columns of Table B and unnest the resulting array and then join or use not in to filter values in Table A:
-- sample data
WITH dataset(column_1) AS (
values ('a'),
('b'),
('c'),
('d'),
('e')
),
dataset2(column_1, column_2) as (
values ('a', array['a', 'b' , 'c', 'd']),
('z', array['c', 'b' , 's', 'f']),
('x', array['g', 'h' , 'i', 'j']),
('y', array['k', 'l' , 'm', 'n']),
('z', array['o', 'p' , 'q', 'r'])
)
-- query
select *
from dataset
where column_1 not in (select distinct col
from dataset2,
unnest(column_1 || column_2) as t(col) );
Output:
column_1
e

Related

Columns data into rows in oracle

Data is present in the screenshot as table format. I want to convert into desired format as mentioned below.
Table describe :
Table A
(branch_code, branch_name, branch_state, hol1, hol2, hol3....hol100)
Expected Output
TAMF046 14/01/2021
TAMF046 15/01/2021
TAMF046 26/01/2021
KERF047 26/01/2021
KERF047 11/03/2021
KERF047 02/04/2021
This is exactly what UNPIVOT is for
with t(id, c1, c2, c3) as (
select 1, 'a', 'b', 'c' from dual union all
select 2, 'aa', 'bb', 'cc' from dual
)
select *
from t
unpivot (
val
for col in (
c1 as 'A1',
c2 as 'A2',
c3 as 'A3'
)
)
val is the new column that will contain values from columns c1 c2 c3.
col is the new column that will contain the name of the column from where the val comes from.
A1 A2 A3 are the values you want to fill in the col for each unpivoted column (these aliases can be omitted if you are ok with the original column names).
Use union
Eg:
select Branch_Code, Hol1 from MyTable
union
select Branch_Code, Hol2 from MyTable
etc
WITH HOLIDAY
AS (
SELECT BRANCH_CODE,HOL1,HOL2,HOL3,HOL4,HOL5,HOL6,HOL7,HOL8,HOL9,HOL10,HOL11,HOL12,HOL13,HOL14,HOL15,HOL16,HOL17,HOL18,HOL19,HOL20,HOL21,HOL22,HOL23,HOL24,HOL25,HOL26,HOL27,HOL28,HOL29,HOL30,HOL31,HOL32,HOL33,HOL34,HOL35,HOL36,HOL37,HOL38,HOL39,HOL40,HOL41,HOL42,HOL43,HOL44,HOL45,HOL46,HOL47,HOL48,HOL49,HOL50,HOL51,HOL52,HOL53,HOL54,HOL55,HOL56,HOL57,HOL58,HOL59,HOL60,HOL61,HOL62,HOL63,HOL64,HOL65,HOL66,HOL67,HOL68,HOL69,HOL70,HOL71,HOL72,HOL73,HOL74,HOL75,HOL76,HOL77,HOL78,HOL79,HOL80,HOL81,HOL82,HOL83,HOL84,HOL85,HOL86,HOL87,HOL88,HOL89,HOL90,HOL91,HOL92,HOL93,HOL94,HOL95,HOL96,HOL97,HOL98,HOL99,HOL100
FROM CUST_HOLIDAY_MASTER
WHERE BRANCH_CODE = I.BRANCH_CODE
)
SELECT BRANCH_CODE , COLVALUE FROM abc
unpivot
( colvalue for col in (HOL1,HOL2,HOL3,HOL4,HOL5,HOL6,HOL7,HOL8,HOL9,HOL10,HOL11,HOL12,HOL13,HOL14,HOL15,HOL16,HOL17,HOL18,HOL19,HOL20,HOL21,HOL22,HOL23,HOL24,HOL25,HOL26,HOL27,HOL28,HOL29,HOL30,HOL31,HOL32,HOL33,HOL34,HOL35,HOL36,HOL37,HOL38,HOL39,HOL40,HOL41,HOL42,HOL43,HOL44,HOL45,HOL46,HOL47,HOL48,HOL49,HOL50,HOL51,HOL52,HOL53,HOL54,HOL55,HOL56,HOL57,HOL58,HOL59,HOL60,HOL61,HOL62,HOL63,HOL64,HOL65,HOL66,HOL67,HOL68,HOL69,HOL70,HOL71,HOL72,HOL73,HOL74,HOL75,HOL76,HOL77,HOL78,HOL79,HOL80,HOL81,HOL82,HOL83,HOL84,HOL85,HOL86,HOL87,HOL88,HOL89,HOL90,HOL91,HOL92,HOL93,HOL94,HOL95,HOL96,HOL97,HOL98,HOL99,HOL100)
)
WHERE COLVALUE IS NOT NULL;
This is the way which i try to this but if anyone has any other way using dynamic query. Please share your views,

Showing NULL on purpose when a NULL joined value is present in SQL

I have a table with some input values and a table with lookup values like below:
select input.value, coalesce(mapping.value, input.value) result from (
select 'a' union all select 'c'
) input (value) left join (
select 'a', 'z' union all select 'b', 'y'
) mapping (lookupkey, value) on input.value = mapping.lookupkey
which gives:
value | result
--------------
a | z
c | c
i.e. I want to show the original values as well as the mapped value but if there is none then show the original value as the result.
The above works well so far with coalesce to determine if there is a mapped value or not. But now if I allow NULL as a valid mapped value, I want to see NULL as the result and not the original value, since it does find the mapped value, only that the mapped value is NULL. The same code above failed to achieve this:
select input.value, coalesce(mapping.value, input.value) result from (
select 'a' union all select 'c'
) input (value) left join (
select 'a', 'z' union all select 'b', 'y' union all select 'c', null
) mapping (lookupkey, value) on input.value = mapping.lookupkey
which gives the same output as above, but what I want is:
value | result
--------------
a | z
c | NULL
Is there an alternative to coalesce that can achieve what I want?
I think you just want a case expression e.g.
select input.[value]
, coalesce(mapping.[value], input.[value]) result
, case when mapping.lookupkey is not null then mapping.[value] else input.[value] end new_result
from (
select 'a'
union all
select 'c'
) input ([value])
left join (
select 'a', 'z'
union all
select 'b', 'y'
union all
select 'c', null
) mapping (lookupkey, [value]) on input.[value] = mapping.lookupkey
Returns:
value result new_result
a z z
c c NULL

How to get unique combinations

This is sample table and I wanted to fetch unique combinations. Need help with SQL query.
a z
b x
c w
d s
e t
z a
x b
w c
s d
t e
Required output:
a z
b x
c w
d s
e t
It looks like you want to select distinct pairs. You first need to transform the pairs a little so that x, y and y, x are treated as identical, then use DISTINCT clause:
CREATE TABLE #t (col1 CHAR(1), col2 CHAR(1));
INSERT INTO #t VALUES
('a', 'z'),
('b', 'x'),
('c', 'w'),
('d', 's'),
('e', 't'),
('z', 'a'),
('x', 'b'),
('w', 'c'),
('s', 'd'),
('t', 'e');
SELECT DISTINCT
CASE WHEN col1 < col2 THEN col1 ELSE col2 END,
CASE WHEN col1 < col2 THEN col2 ELSE col1 END
FROM #t
You seem to have complete duplicates, so just use <:
select a, b
from t
where a < b;
If you don't have complete duplicates and you want to preserve the original values, I recommend union all:
select a, b
from t
where a < b
union all
select a, b
from t
where a > b and
not exists (select 1 from t t2 where t2.a = t.b and t2.b = t.a);
Or use a combination of the attempts:
select col1, col2 from t where col1 < col2
union
select col2, col1 from t where col1 >= col2;
This will work if you have only duplicates or if some combinations are only once in your table.

sql generate code based on three column values

I have three columns
suppose
row no column1 column2 column3
1 A B C
2 A B C
3 D E F
4 G H I
5 G H C
I want to generate code by combining these three column values
For Eg.
1)ABC001
2)ABC002
3)DEF001
4)GHI001
5)GHC001
by checking combination of three columns
logic is that
if values of three columns are same then like first time it shows 'ABC001'
and 2nd time it shows 'ABC002'
You can try this:
I dont know what you want for logic with 00, but you can add them manuel or let the rn decide for you
declare #mytable table (rowno int,col1 nvarchar(50),col2 nvarchar(50),col3 nvarchar(50)
)
insert into #mytable
values
(1,'A', 'B', 'C'),
(2,'A', 'B', 'C'),
(3,'D', 'E', 'F'),
(4,'G', 'H', 'I'),
(5,'G', 'H', 'C')
Select rowno,col1,col2,col3,
case when rn >= 10 and rn < 100 then concatcol+'0'+cast(rn as nvarchar(50))
when rn >= 100 then concatcol+cast(rn as nvarchar(50))
else concatcol+'00'+cast(rn as nvarchar(50)) end as ConcatCol from (
select rowno,col1,col2,col3
,Col1+col2+col3 as ConcatCol,ROW_NUMBER() over(partition by col1,col2,col3 order by rowno) as rn from #mytable
) x
order by rowno
My case when makes sure when you hit number 10 it writes ABC010 and when it hits above 100 it writes ABC100 else if its under 10 it writes ABC001 and so on.
Result
TSQL: CONCAT(column1,column2,column3,RIGHT(REPLICATE("0", 3) + LEFT(row_no, 3), 3))
You should combine your columns like below :
SELECT CONVERT(VARCHAR(MAX), ROW_NUMBER() OVER(ORDER BY
(
SELECT NULL
)))+') '+DATA AS Data
FROM
(
SELECT column1+column2+column3+'00'+CONVERT(VARCHAR(MAX), ROW_NUMBER() OVER(PARTITION BY column1,
column2,
column3 ORDER BY
(
SELECT NULL
))) DATA
FROM <table_name>
) T;
Result :
1)ABC001
2)ABC002
3)DEF001
4)GHI001
5)GHC001
MySQL:
CONCAT(column1,column2,column3,LPAD(row_no, 3, '0'))
[you will need to enclose the 'row no' in ticks if there is a space in the name of the field instead of underscore.]

SQL Querying on tuple values

I need to write a write a SQL query that selects values from a table based on several tuples of selection criteria. It could be done using a where clause like this :
where (a = 1 and b='a') or (a=5 and b='s')
Is the best way to select:
select a, pk from x where a in (1,5)
select b, pk from x where b in ('a','s')
and join the result of the two queries using the primary key?
do you mean something(a self join) like this:
select x.a, x.pk
from x
join x x2 on x.pk=x2.pk
where x.a in (1,5)
and x2.b in ('a','s')
?
You can use join on table expression from VALUES. You can add in VALUES as much rows as you want. It will work on MSSQL:
DECLARE #x TABLE ( a INT, b CHAR(1) )
INSERT INTO #x
VALUES ( 1, 'a' ),
( 1, 'b' ),
( 1, 'c' ),
( 2, 'd' ),
( 2, 'e' ),
( 5, 'f' ),
( 5, 's' )
SELECT x.*
FROM #x x
JOIN (
VALUES ( 1, 'a'),
( 5, 's')
) AS v( a, b ) ON x.a = v.a AND x.b = v.b
Output:
a b
1 a
5 s
Based on my understanding you want write a SQL that uses a combination of two filters. Here is a simple solution that will work in any database.
Create a new column say "COLUMN_NEW" in the same table or build a temp table or a view with a new column (plus existing columns from original table).
Insert concatenated values of column a and column b in "COLUMN_NEW". Based on the example mentioned by you values in "COLUMN_NEW" will be "1a" and "5s"
Now you may have a different syntax for concat in different databases. Example concat(a,b) in SQL server.
SQL to select records from the table will be select * from table where COLUMN_NEW in ("1a",5s");