我有两张桌子
C1 C2 Value
All All 5
da All 6
和表b
C1 C2
cc a
da b
我想得到表b的匹配值
C1 C2 Value
cc a 5
da b 6
我写了一个像这样的查询
select b.*,a.* from a, b
where 1=(case when a.C1=b.C1 then 1
when a.C1='All' then 1
else 0)
and 1=(case when a.C2=b.C2 then 1
when a.C2='All' then 1
else 0)
并得到了结果
C1 C2 Value
cc a 5
da b 6
da b 5
如何获得查询以获得结果如下
C1 C2 Value
cc a 5
da b 6
基本上当使用匹配值匹配时,否则使用默认值'全部',非常感谢!
答案 0 :(得分:0)
您所需的输出对我来说不是很清楚,但也许你需要这样的东西:
select c1, c2 , value from
(
select b.c1, b.c2, a.value,
row_number() over ( partition by decode(a.c1, 'all', 0, 1) + decode(a.c2, 'all', 0, 1)
order by decode(a.c1, 'all', 0, 1) + decode(a.c2, 'all', 0, 1) desc
) as num
from a join b
on ( a.c1 = 'all' OR a.c1 = b.c1) and
( a.c2 = 'all' OR a.c2 = b.c2)
)
where num = 1;
希望这有帮助
答案 1 :(得分:0)
有点不寻常的加入标准。如果性能不是限制,那么带有合并的左外连接可能是获得所需内容的简单方法。
select b.*, COALESCE(a1.Value, a2.Value, a3.Value, a4.Value)
from b LEFT OUTER JOIN a a1
ON a1.C1=b.C1 AND a1.C2=b.C2
LEFT OUTER JOIN a a2
ON a2.C1=b.C1 AND a2.C2='All'
LEFT OUTER JOIN a a3
ON a3.C1='All' AND a3.C2=b.C2
LEFT OUTER JOIN a a4
ON a4.C1='All' AND a4.C2='All'
请注意,如果有以下内容,您将获得多行:
答案 2 :(得分:0)
Oracle安装程序:
CREATE TABLE table_a ( C1, C2, Value ) AS
SELECT 'All', 'All', 5 FROM DUAL UNION ALL
SELECT 'da', 'All', 6 FROM DUAL UNION ALL
SELECT 'da', 'b', 4 FROM DUAL;
CREATE TABLE table_b ( C1, C2 ) AS
SELECT 'cc', 'a' FROM DUAL UNION ALL
SELECT 'da', 'b' FROM DUAL UNION ALL
SELECT 'da', 'c' FROM DUAL;
<强>查询强>:
SELECT b.C1,
b.C2,
( SELECT MAX ( value ) KEEP (
DENSE_RANK FIRST
ORDER BY
CASE WHEN b.C1 = a.C1 AND b.C2 = a.C2 THEN 1
WHEN b.C1 = a.C1 THEN 2
ELSE 3
END ASC
)
FROM table_a a
WHERE ( b.C1 = a.C1 AND b.C2 = a.C2 )
OR ( b.C1 = a.C1 AND a.C2 = 'All' )
OR ( a.C1 = 'All' AND a.C2 = 'All' )
) AS Value
FROM table_b b;
<强>结果:
C1 C2 VALUE
-- -- ----------
cc a 5
da b 4
da c 6
查询2 :
SELECT b.C1,
b.C2,
MAX ( value ) KEEP (
DENSE_RANK FIRST
ORDER BY
CASE WHEN b.C1 = a.C1 AND b.C2 = a.C2 THEN 1
WHEN b.C1 = a.C1 THEN 2
ELSE 3
END ASC
) AS Value
FROM table_b b
INNER JOIN
table_a a
ON ( b.C1 = a.C1 AND b.C2 = a.C2 )
OR ( b.C1 = a.C1 AND a.C2 = 'All' )
OR ( a.C1 = 'All' AND a.C2 = 'All' )
GROUP BY b.C1, b.C2;
查询3 :
SELECT C1,
C2,
Value
FROM (
SELECT b.C1,
b.C2,
value,
ROW_NUMBER() OVER (
PARTITION BY b.C1, b.C2
ORDER BY CASE WHEN b.C1 = a.C1 AND b.C2 = a.C2 THEN 1
WHEN b.C1 = a.C1 THEN 2
ELSE 3
END ASC
) AS RN
FROM table_b b
INNER JOIN
table_a a
ON ( b.C1 = a.C1 AND b.C2 = a.C2 )
OR ( b.C1 = a.C1 AND a.C2 = 'All' )
OR ( a.C1 = 'All' AND a.C2 = 'All' )
)
WHERE rn = 1;
所有人都应该给出相同的结果。
答案 3 :(得分:0)
试试这个:
NumberOfProcessors