как взять несколько строк из запроса и проанализировать их на 1 строку в новом запросе - PullRequest
0 голосов
/ 24 февраля 2020

Я разработал запрос для решения проблемы ниже. Тем не менее, он не показывает желаемых результатов. У кого-нибудь есть идеи?

Таблица 1

ID FRUIT 
1  APPLE
1  APPLE
1  MANGO

Таблица 2

country  id
USA       1
UK        2

Если количество названий фруктов больше 1, мне нужно «да» для фестиваля и «нет» для нуля.

select country ,id 
CASE 
when table1.count > 1 and table1.fruit='APPLE' 
then 'Y'
else 'N'
END as apple_festival,
CASE 
when table1.count > 1 and table1.fruit='MANGO' 
then 'Y'
else 'N'
END as mango_festival,
CASE 
when table1.count > 1 and table1.fruit='BANANA' 
then 'Y'
else 'N'
END as Banana festival, JOIN (SELECT id,fruit,count from table1  group by id,fruit) table1 on table1.id=table2.id

Я хочу получить результаты, подобные этому:

COUNTRY id apple_festival mango_festival Banana_festival
USA     1         Y            Y              N

Однако я получаю это:

COUNTRY id apple_festival mango_festival Banana_festival
USA     1         Y            N              N
USA     1         N            Y              N

люди могут использовать эта скрипка за помощь мне ..

Ответы [ 2 ]

0 голосов
/ 24 февраля 2020

Попробуйте приведенный ниже запрос. Работает на SQL сервере.

  select  country,ID,
  apple_festival =Case when max(case when Fruit='Apple' and cnt>=1  then 1 end)=1 then 'Yes' Else 'No' End,
  Mango_festival =Case when max(case when Fruit='Mango' and cnt>=1  then 1 end)=1 then 'Yes' Else 'No' End,   
  Banana_festival =Case when max(case when Fruit='Banana' and cnt>=1  then 1 end)=1 then 'Yes' Else 'No' End   
from table2 mt1
cross apply (
    select FRUIT,cnt=count(*) from table1 mt2  
    where mt2.id=mt1.id
    group by FRUIT
) as fruittable                    
 group by country,ID

Пожалуйста, убедитесь, что счетчик логики c (будь то "> = 1" или "> 1")

0 голосов
/ 24 февраля 2020

Вы можете сделать условное агрегирование:

select
    t2.country,
    t2.id,
    case when max(case when t1.fruit = 'apple'  then 1 end) = 1 then 'Yes' else 'No' end apple_festival,
    case when max(case when t1.fruit = 'mango'  then 1 end) = 1 then 'Yes' else 'No' end mango_festival,
    case when max(case when t1.fruit = 'banana' then 1 end) = 1 then 'Yes' else 'No' end banana_festival
from table2 t2
inner join table1 t1 on t1.id = t2.id
group by t2.id, t2.country
...