【问题标题】:how to take multiple rows from a query and and analyze it for 1 row in new query如何从查询中获取多行并在新查询中分析 1 行
【发布时间】:2020-02-24 08:52:14
【问题描述】:

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

表 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

人们可以用这个小提琴来帮助我..

【问题讨论】:

  • 您使用的是哪种 DBMS 产品? “SQL”只是一种查询语言,而不是特定数据库产品的名称。请为您正在使用的数据库产品添加tagWhy should I tag my DBMS
  • 您的结果表明条件是> 0,而不是> 1——这是非常不同的。

标签: sql group-by pivot sybase


【解决方案1】:

你可以做条件聚合:

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

【讨论】:

  • 群里应该有更多apple_festival和香蕉节之类的吧。并且上面的查询没有运行。你可以检查下面的小提琴[链接](dbfiddle.uk/…
  • @amarenderreddyjali:我编辑了查询,使其在 Oracle 上运行。
【解决方案2】:

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

  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”)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-12
    • 2017-09-22
    • 2023-04-03
    • 2021-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多