Apply value to group - sql

need help with,
if any ID with same Groupid has Yes in Payable, add Yes value to Results, otherwise blank.
This should be applicable for hundreds of IDs grouped in hundreds of GroupIDs.
ID
GroupID
Payable
Result
111
a
Yes
Yes
222
a
Yes
333
a
Yes
444
b
Yes
555
b
Yes
Yes
777
b
Yes
888
c
I tried to group based on groupID and created a case where groupId count equals or is higher as 1 and the eligibility is Yes.

Your question is a bit unclear due to lack of information about constraints, all the values in table etc.
With the given information tho, your task might be done by following query:
with groupData as
(
Select groupid,payable from put_your_table_name_here
where payable is not null
group by groupid
)
Select pt.id
,pt.groupId
,gd.payable
,pt.result
from put_your_table_name_here pt
left join groupData gd on gd.groupid=pt.groupid
The query has it drawbacks- you should give some more info about constraints, but generally it should work.
If you wouldnt want to have null values in payable column, you could change left join to join.

WITH CTE(ID, GroupID, Payable)AS
(
SELECT 111,'A','YES'
UNION ALL
SELECT 222,'A',''
UNION ALL
SELECT 333,'A',''
UNION ALL
SELECT 444,'B',''
UNION ALL
SELECT 555,'B','YES'
UNION ALL
SELECT 777,'B',''
UNION ALL
SELECT 888,'C',''
)
SELECT C.ID,C.GroupID,C.Payable,F.FLAG
FROM CTE AS C
JOIN
(
SELECT X.GROUPID,MAX(PAYABLE)FLAG
FROM CTE AS X
GROUP BY X.GroupID
)F ON C.GroupID=F.GroupID
ORDER BY C.ID;
You can try something like this
or
SELECT C.ID,C.GroupID,C.Payable,
FIRST_VALUE(C.PAYABLE)OVER(PARTITION BY C.GROUPID ORDER BY C.PAYABLE DESC)XCOL
FROM CTE AS C
ORDER BY C.ID;

with data (ID,GroupID,Payable) as (
Select 111, 'a', 'Yes' from dual union all
Select 222, 'a', null from dual union all
Select 333, 'a', null from dual union all
Select 444, 'b', null from dual union all
Select 555, 'b', 'Yes' from dual union all
Select 777, 'b', null from dual union all
Select 888, 'c', null from dual
)
,result as(
select GroupID, case when Count(*) > 1 then 'Yes' else null end Result
from data
group by GroupID)
Select * from data
Join result on data.GroupID = result.GroupID
order by data.ID,data.GroupID
Db fiddle link

Related

How to select a record which have all id's in SQL?

I want select record which have all id's.
Example:
Name
ID
Ram
3
Ajay
1
Mogan
3
Ram
1
Ram
2
Here Ram have all id's (1,2,3). So, I want result as Ram.
WITH CTE(NAME,CODE)AS
(
SELECT 'RAM',1 UNION ALL
SELECT'AJAY',3 UNION ALL
SELECT 'MOGAN',2 UNION ALL
SELECT 'KUMAR',3 UNION ALL
SELECT 'RAM',2 UNION ALL
SELECT 'JAYA',1 UNION ALL
SELECT 'KABIL',3 UNION ALL
SELECT 'RAM',3
)
SELECT C.NAME
FROM CTE AS C
GROUP BY C.NAME
HAVING COUNT(DISTINCT C.CODE)=(SELECT COUNT(DISTINCT CODE) FROM CTE )
As far as I know, this is called "relational division". You can try my query or look for another possible solution
Select * from table where upper(name) = 'RAM'
This query would bring back all the IDs for RAM alone
how about string agg.
CREATE TABLE MyTable (
ID int,
Name varchar(255),
);
Insert into MyTable(ID, Name) values (1, 'Ram');
Insert into MyTable(ID, Name) values (2, 'Ram');
Insert into MyTable(ID, Name) values (3, 'Ram');
Insert into MyTable(ID, Name) values (1, 'Ajay');
Insert into MyTable(ID, Name) values (1, 'Mogan');
select Name, string_agg(ID, ',') as Ids
from MyTable
group by Name;
result
Ajay 1
Mogan 1
Ram 1,2,3
see result here
http://sqlfiddle.com/#!18/923bf/4
With reference to the with clause used by #surgey above,
WITH CTE(NAME,CODE)AS
(
SELECT 'RAM',1 from dual UNION ALL
SELECT'AJAY',3 from dual UNION ALL
SELECT 'MOGAN',2 from dual UNION ALL
SELECT 'KUMAR',3 from dual UNION ALL
SELECT 'RAM',2 from dual UNION ALL
SELECT 'JAYA',1 from dual UNION ALL
SELECT 'KABIL',3 from dual UNION ALL
SELECT 'RAM',3 from dual
)
select name, code, rank() over(partition by name order by code) rank
from cte
this query, it will bring back everybody in the and group them by name. THis could be one possible solution other use tou can use an "IN" clause in your where as shown below
Select * from table where upper(name) in ('RAM','AJAY')
If are you using MySql this will solve your issue:
SELECT r1.name
FROM raws r1
LEFT JOIN raws r2 ON r1.id = r2.id AND r1.name = r2.name
WHERE r2.id IN (1, 2, 3)
GROUP by r1.name
HAVING count(r2.id) = 3; # count of numbers in IN (1, 2, 3)
And if you have identifier in your table use it for join instead
of r1.id = r2.id AND r1.name = r2.name

How to compare column in one table with array from another table in BigQuery?

Just continue from the answer for my previous question.
I want to get all values from table b (in rows) if there is any difference between values in arrays from table a by same ids
WITH a as (SELECT 1 as id, ['123', 'abc', '456', 'qaz', 'uqw'] as value
UNION ALL SELECT 2, ['123', 'wer', 'thg', '10', '200']
UNION ALL SELECT 3, ['200']
UNION ALL SELECT 4, null
UNION ALL SELECT 5, ['140']),
b as (SELECT 1 as id, '123' as value
UNION ALL SELECT 1, 'abc'
UNION ALL SELECT 1, '456'
UNION ALL SELECT 1, 'qaz'
UNION ALL SELECT 1, 'uqw'
UNION ALL SELECT 2, '123'
UNION ALL SELECT 2, 'wer'
UNION ALL SELECT 2, '10'
UNION ALL SELECT 3, null
UNION ALL SELECT 4, 'wer'
UNION ALL SELECT 4, '234'
UNION ALL SELECT 5, '140'
UNION ALL SELECT 5, '121'
)
SELECT * EXCEPT(flag)
FROM (
SELECT b.*, COUNTIF(b.value IS NULL) OVER(PARTITION BY id) flag
FROM a LEFT JOIN a.value
FULL OUTER JOIN b
USING(id, value)
)
WHERE flag > 0
AND NOT id IS NULL
It works well for all ids except 5.
In my case I need to return all values if there is any difference.
In example array with id 5 from table a has only one value is '140' while there are two rows with values by id 5 from table b. So in this case all values by id 5 from table b also must appear in expected output
How need to modify this query to get what I want?
UPDATED
Seems like it works for me. But I can not be sure for 100%
SELECT * EXCEPT(flag)
FROM (
SELECT b.*, COUNTIF((b.value IS NULL AND a.value IS NOT NULL) OR (b.value IS NOT NULL AND a.value IS NULL)) OVER(PARTITION BY id) flag
FROM a LEFT JOIN a.value
FULL OUTER JOIN b
USING(id, value)
)
WHERE flag > 0
AND NOT id IS NULL
#standardSQL
SELECT *
FROM table_b
WHERE id IN (
SELECT id FROM table_a a
JOIN table_b b USING(id)
GROUP BY id
HAVING STRING_AGG(IFNULL(b.value, 'NULL') ORDER BY b.value) !=
IFNULL(ANY_VALUE((SELECT STRING_AGG(IFNULL(value, 'NULL') ORDER BY value) FROM a.value)), 'NULL')
)

How to group by and select

I tried to extract customer who has type a
I guess I must group by in customer and tried to having in type
customer type
A a
A c
B b
B c
C a
C a
but I couldn't figure out specific way to achieve this.
If someone has opinion,please let me know.
My desired result is following
customer type
A a
A c
C a
C a
Thanks
Using exists, we can try:
SELECT t1.customer, t1.type
FROM yourTable t1
WHERE EXISTS (SELECT 1 FROM yourTable t2 WHERE t2.customer = t1.customer AND t2.type = 'a');
The exists logic reads in plain English as select any record for which we can find at least one record for the same customer whose type is a. This means retain all customer records, where at least one of those records has type a.
You don't need to group. You can just filter the table for customers that have type 'a' and use that resultset to filter the table again for the customers.
WITH
cust_data
AS
(SELECT 'A' AS customer, 'a' AS TYPE FROM DUAL
UNION ALL
SELECT 'A' AS customer, 'c' AS TYPE FROM DUAL
UNION ALL
SELECT 'B' AS customer, 'b' AS TYPE FROM DUAL
UNION ALL
SELECT 'B' AS customer, 'c' AS TYPE FROM DUAL
UNION ALL
SELECT 'C' AS customer, 'a' AS TYPE FROM DUAL
UNION ALL
SELECT 'C' AS customer, 'a' AS TYPE FROM DUAL)
SELECT *
FROM cust_data c
WHERE customer IN (SELECT customer
FROM cust_data
WHERE TYPE = 'a');
This gives
CUSTOMER TYPE
A c
A a
C a
C a
I hope the below query completes your requirement.
SELECT
*
FROM
test.customer
WHERE
customer IN (SELECT
customer
FROM
test.customer
WHERE
type = 'a');
Output:
A a
A c
C a
C a
Do not use accessing table twice. Use window functions instead.
with t(customer, type) as (
select 'A', 'a' from dual union all
select 'A', 'c' from dual union all
select 'B', 'b' from dual union all
select 'B', 'c' from dual union all
select 'C', 'a' from dual union all
select 'C', 'a' from dual)
select customer, type
from
(select t.*, count(decode(type, 'a', 1)) over (partition by customer) cnt
from t
)
where cnt > 0;
CUSTOMER TYPE
-------- ----
A a
A c
C a
C a

How to get an accurate JOIN using Fuzzy matching in Oracle

I'm trying to join a set of county names from one table with county names in another table. The issue here is that, the county names in both tables are not normalized. They are not same in count; also, they may not be appearing in similar pattern always. For instance, the county 'SAINT JOHNS' in "Table A" may be represented as 'ST JOHNS' in "Table B". We cannot predict a common pattern for them.
That means , we cannot use "equal to" (=) condition while joining. So, I'm trying to join them using the JARO_WINKLER_SIMILARITY function in oracle.
My Left Outer Join condition would be like:
Table_A.State = Table_B.State
AND UTL_MATCH.JARO_WINKLER_SIMILARITY(Table_A.County_Name,Table_B.County_Name)>=80
I've given the measure 80 after some testing of the results and it seemed to be optimal.
Here, the issue is that I'm getting set of "false Positives" when joining. For instance, if there are some counties with similarity in names under the same state ("BARRY'and "BAY" for example), they will be matched if the measure is >=80.
This creates inaccurate set of joined data.
Can anyone please suggest some work around?
Thanks,
DAV
Can you plz help me to build a query that will lookup Table_A for each record in Table B/C/D, and match against the county name in A with highest ranked similarity that is >=80
Oracle Setup:
CREATE TABLE official_words ( word ) AS
SELECT 'SAINT JOHNS' FROM DUAL UNION ALL
SELECT 'MONTGOMERY' FROM DUAL UNION ALL
SELECT 'MONROE' FROM DUAL UNION ALL
SELECT 'SAINT JAMES' FROM DUAL UNION ALL
SELECT 'BOTANY BAY' FROM DUAL;
CREATE TABLE words_to_match ( word ) AS
SELECT 'SAINT JOHN' FROM DUAL UNION ALL
SELECT 'ST JAMES' FROM DUAL UNION ALL
SELECT 'MONTGOMERY BAY' FROM DUAL UNION ALL
SELECT 'MONROE ST' FROM DUAL;
Query:
SELECT *
FROM (
SELECT wtm.word,
ow.word AS official_word,
UTL_MATCH.JARO_WINKLER_SIMILARITY( wtm.word, ow.word ) AS similarity,
ROW_NUMBER() OVER ( PARTITION BY wtm.word ORDER BY UTL_MATCH.JARO_WINKLER_SIMILARITY( wtm.word, ow.word ) DESC ) AS rn
FROM words_to_match wtm
INNER JOIN
official_words ow
ON ( UTL_MATCH.JARO_WINKLER_SIMILARITY( wtm.word, ow.word )>=80 )
)
WHERE rn = 1;
Output:
WORD OFFICIAL_WO SIMILARITY RN
-------------- ----------- ---------- ----------
MONROE ST MONROE 93 1
MONTGOMERY BAY MONTGOMERY 94 1
SAINT JOHN SAINT JOHNS 98 1
ST JAMES SAINT JAMES 80 1
Using some made up test data inline (you would use your own TABLE_A and TABLE_B in place of the first two with clauses, and begin at with matches as ...):
with table_a (state, county_name) as
( select 'A', 'ST JOHNS' from dual union all
select 'A', 'BARRY' from dual union all
select 'B', 'CHEESECAKE' from dual union all
select 'B', 'WAFFLES' from dual union all
select 'C', 'UMBRELLAS' from dual )
, table_b (state, county_name) as
( select 'A', 'SAINT JOHNS' from dual union all
select 'A', 'SAINT JOANS' from dual union all
select 'A', 'BARRY' from dual union all
select 'A', 'BARRIERS' from dual union all
select 'A', 'BANANA' from dual union all
select 'A', 'BANOFFEE' from dual union all
select 'B', 'CHEESE' from dual union all
select 'B', 'CHIPS' from dual union all
select 'B', 'CHICKENS' from dual union all
select 'B', 'WAFFLING' from dual union all
select 'B', 'KITTENS' from dual union all
select 'C', 'PUPPIES' from dual union all
select 'C', 'UMBRIA' from dual union all
select 'C', 'UMBRELLAS' from dual )
, matches as
( select a.state, a.county_name, b.county_name as matched_name
, utl_match.jaro_winkler_similarity(a.county_name,b.county_name) as score
from table_a a
join table_b b on b.state = a.state )
, ranked_matches as
( select m.*
, rank() over (partition by m.state, m.county_name order by m.score desc) as ranking
from matches m
where score > 50 )
select rm.state, rm.county_name, rm. matched_name, rm.score
from ranked_matches rm
where ranking = 1
order by 1,2;
Results:
STATE COUNTY_NAME MATCHED_NAME SCORE
----- ----------- ------------ ----------
A BARRY BARRY 100
A ST JOHNS SAINT JOHNS 80
B CHEESECAKE CHEESE 92
B WAFFLES WAFFLING 86
C UMBRELLAS UMBRELLAS 100
The idea is matches computes all scores, ranked_matches assigns them a sequence within (state, county_name), and the final query picks all the top scorers (i.e. filters on ranking = 1).
You may still get some duplicates as there is nothing to stop two different fuzzy matches scoring the same.

Oracle UNION ALL preservation of the order of records in query

I have the following scenario(table below) where I would like to pick 'X' or 'Y' based on whether they are NULL or not.
X Y pick
null not null Y
not null not null X
not null null X
the rows containing the data 'X' and 'Y' or UNION ALLed like below:
select 'X' as a
union all
select 'Y' as a
So I tried and got the following SQL but not sure about the "rownum<=1" part. This will work(for the case where both X and Y are not null) only if UNION ALL preserve
the order in which I query the two rows.
select a from
(
select 'X' as a
union all
select 'Y' as a
) where a is not null and rownum<=1;
select a from
(
select null as a
union all
select 'Y' as a
) where a is not null and rownum<=1;
select a from
(
select 'X' as a
union all
select null as a
) where a is not null and rownum<=1;
Is the above right way to go about this?. Any insight would be much appreciated
If you want a specific order in SQL, you have to ask for it. You could probably extend your union as:
select a from (
select a,rownum as rn from
(
select 'X' as a, 0 as Priority from dual
union all
select 'Y' as a, 1 as Priority from dual
) where a is not null order by Priority
) where rn = 1
Although I admit I'm not great with Oracle. I believe rownum does odd things in WHERE clauses, that's why I've introduced an extra level of querying.
Coalesce
http://download.oracle.com/docs/cd/B28359_01/server.111/b28286/functions023.htm