[英]Outer Join on two columns with default value if one column is null
I have two tables - one a transaction table, and the other a look-up table. 我有两个表-一个是事务表,另一个是查询表。 These tables join on two columns, one of which always has a value, while the other may not.
这些表连接在两列上,其中一列始终具有一个值,而另一列则可能没有。
Sample this 试一下
transaction table
category | subcategory | marks A | 01 | 10 A | 02 | 20 B | 03 | 30 B | 04 | 40 C | 05 | 50
lookup table
category | subcategory | cut-off A | | 15 A | 01 | 25 B | 03 | 35 B | | 55 C | | 75
I wish to get the cut-off next to each entry in the transaction
table by joining the category
and subcategory
columns. 我希望通过合并
category
和subcategory
列来获得transaction
表中每个条目旁边的subcategory
。 For cases where subcategory
does not have an exact match, the record corresponding to null
needs to be picked. 对于
subcategory
不完全匹配的情况,需要选择与null
对应的记录。
Desired output format: 所需的输出格式:
output format
category | subcategory | marks | cut-off A | 01 | 10 | 25 A | 02 | 20 | 15 B | 03 | 30 | 35 B | 04 | 40 | 55 C | 05 | 50 | 75
I have been trying to think along the lines of a query like the one below, the problem of course is it doesn't work the way I want it to as it doesn't handle the null case right. 我一直在尝试像下面这样的查询思路,问题当然是它不能按我想要的方式工作,因为它不能正确处理空值。
select t.category, t.subcategory, t.marks, l.cut-off from transaction t left outer join lookup l on t.category = l.category and t.subcategory = l.subcategory
Do I need multiple queries (like a union all
that handles null
and not null
separately? Are there options that work with single query? 我是否需要多个查询(例如,一个
union all
not null
分别处理null
和not null
?是否有适用于单个查询的选项?
您可以这样做:
SELECT t.category, t.subcategory, t.marks, l.cut-off FROM transaction t left outer join lookup l on t.category = l.category and t.subcategory = ISNULL(l.subcategory, t.subcategory)
Using a sub query (NVL for oracle) 使用子查询(对于Oracle为NVL)
SELECT t.category,
t.subcategory,
t.marks,
NVL(
(SELECT l.cut_OFF from lookup l where l.category = t.category and l.subcategory = t.subcategory),
(SELECT l.cut_OFF from lookup l where l.category = t.category and l.subcategory is null))
FROM transaction t
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.