Sql 如何使用Oracle Join和Case仅返回1行?
我有一个案子。检查下表:Sql 如何使用Oracle Join和Case仅返回1行?,sql,oracle,Sql,Oracle,我有一个案子。检查下表: Table Jeans unique on onwer and Source -------------------------------- ID | Source | Prices | Owner 1 | Macy | 23 | 1 2 | Nike | 25 | 1 3 | KFC | 12 | 1 Table Pant unique on onwer and Source ------------------
Table Jeans unique on onwer and Source
--------------------------------
ID | Source | Prices | Owner
1 | Macy | 23 | 1
2 | Nike | 25 | 1
3 | KFC | 12 | 1
Table Pant unique on onwer and Source
--------------------------------
ID | Source | Prices | Owner
1 | Macy | 10 | 1
2 | Nike | 28 | 1
3 | KFC | 19 | 1
Table Owner
--------------------------------
ID | Name |
1 | John |
注意:牛仔裤和裤子不一定有三种来源。
所以我们有这样的桌子,在第1页:*裤子和牛仔裤。逻辑如下:
Select o1.name,
case when j1.source = 'Macy' then j1.prices #1 if Macy has Jeans, pick Jeans from Macy and end
when p1.source = 'Macy' then p1.prices #2 if Macy doesn't has Jeans but has Pant, pick Pant from Macy and end
when j1.source = 'Nike' then j1.prices #3
when p1.source = 'Nike' then p1.prices #4
when j1.source = 'KFC' then j1.prices #5
when p1.source = 'KFC' then p1.prices #6
END AS Money
from Owner o1, Jeans j1, Pant p1
where o1.ID = j1.ID and p1.ID = o1.ID;
我希望结果是:
|Name | Money |
|John | 23 |
because according to the logic, Macy first, then Jeans. If Macy doesn't have Jeans, then it will be Macy Pant 10.
不幸的是,上面的SQL返回所有6行。我希望案件按顺序进行,案件的顺序很重要,如果继续1适合,只需返回1并转到下一个所有者
Java
if(jeans.source = "Macy") {
return jeans.price;
} else if(pant.source = "Macy") {
return pant.price;
} else {
if(jeans.source = "Nike") {
return jeans.price;
} else if(pant.source = "Nike") {
return pant.price;
} else {
if(jeans.source = "KFC") {
return jeans.price;
} else if(pant.source = "KFC") {
return pant.price;
}
}
}
我真的需要这方面的帮助,我必须在SQL中执行这样的逻辑。您不必使用我的case-SQL,只要SQL提供正确的输出就好
谢谢。您的表
裤子
应该是可选的,我们将使用左连接。然后coalesce()
函数在裤子
之前先检查牛仔裤
。一个子查询
,首先根据项目类型生成排序器
select t1.name, t1.price from (
select t1.name
, coalesce(t2.price, t3.price) as price
, case when t2.source='Macy' then 1
when t2.source='Nike' then 2
when t2.source='KFC' then 3
else 100
end as sortorder
from Owner t1
inner join Jeans t2 on t2.ID = t1.ID
left join Pant t3 on t3.ID = t1.ID) t1
where rownum = 1
order by t1.sortorder asc
谢谢我会在工作中试一试。我还更新了我的问题。这不是一个开关盒,更多的是如果其他。此外,牛仔裤和裤子在所有者和来源上都是独一无二的。