SQL - Get the values of another column for values in a given column
-
16-03-2021 - |
Pergunta
I am working with a large data table. I want to check the individual items with their destination and the count of destinations if there are more than 1 destination for a given item.
So in the below image, in my result, I should not get Items Grapes and Rice since there is only one destination for them. I want to filter by the destination as well. I need to remove the items which are going to the same destination. So here, only Apple and their respective destinations are the ones I need. Orange should be removed because its going to the same destination.
The query I have written is below. However it does not serve the purpose.This does not filter out same destinations. Any help please ?
select Item,
listagg(Destination, ',') within group (order by Destination) as Destination
from ProductsTable
group by Item
Solução
with data as
(
select 'Apple' as item, 'Rome' as destination from dual union all
select 'Apple' as item, 'Barcelona' as destination from dual union all
select 'Apple' as item, 'Moscow' as destination from dual union all
select 'Apple' as item, 'Paris' as destination from dual union all
select 'Apple' as item, 'London' as destination from dual union all
select 'Orange' as item, 'Cairo' as destination from dual union all
select 'Orange' as item, 'Cairo' as destination from dual union all
select 'Orange' as item, 'Cairo' as destination from dual union all
select 'Grapes' as item, 'Berlin' as destination from dual union all
select 'Rice' as item, 'Manila' as destination from dual
)
select Item,
listagg(Destination, ',') within group (order by Destination) as Destination
from data
group by Item having count(distinct destination) > 1;
ITEM DESTINATION
------ --------------------------------------------------
Apple Barcelona,London,Moscow,Paris,Rome
Licenciado em: CC-BY-SA com atribuição
Não afiliado a dba.stackexchange