如何从查询中获取多行并在新查询中分析它的 1 行

how to take multiple rows from a query and and analyze it for 1 row in new query

我针对以下问题开发了一个查询。但是,它没有显示出预期的结果。有人有想法吗?

table 1

ID FRUIT 
1  APPLE
1  APPLE
1  MANGO

Table 2

country  id
USA       1
UK        2

如果水果名称的计数大于 1,我需要 "yes" 表示节日,"no" 表示零计数。

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

人们可以使用这个 fiddle 来帮助我..

您可以进行条件聚合:

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

试试下面的查询。 运行 在 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

请确保计数逻辑(无论是“>=1”还是“>1”)