首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何从查询中提取多行,并在新查询中对1行进行分析

如何从查询中提取多行,并在新查询中对1行进行分析
EN

Stack Overflow用户
提问于 2020-02-24 08:52:14
回答 2查看 43关注 0票数 0

我已经为下面的问题开发了一个查询。然而,它并没有显示出预期的结果。有人有主意吗?

表1

代码语言:javascript
复制
ID FRUIT 
1  APPLE
1  APPLE
1  MANGO

表2

代码语言:javascript
复制
country  id
USA       1
UK        2

如果水果名称大于1,我需要“是”表示节日,“否”表示“零计数”。

代码语言:javascript
复制
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

我想要这样的结果:

代码语言:javascript
复制
COUNTRY id apple_festival mango_festival Banana_festival
USA     1         Y            Y              N

不过,我明白这一点:

代码语言:javascript
复制
COUNTRY id apple_festival mango_festival Banana_festival
USA     1         Y            N              N
USA     1         N            Y              N

人们可以用这把小提琴来帮助我。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-02-24 09:01:19

您可以进行条件聚合:

代码语言:javascript
复制
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
票数 0
EN

Stack Overflow用户

发布于 2020-02-24 10:48:47

尝试下面的查询。在Server中运行。

代码语言:javascript
复制
  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”)

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60372313

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档