我在一个表Test中有三列
name, type, region
示例值为:
john IT ny
john SALES ny
john FINANCE ny
lisa SALES ny
lisa FINANCE ny
出于上述情况,我如何优先考虑IT,2优先考虑销售,3代理财务。
我的意思是上面的样本记录,它给出了2条记录
John IT ny
Lisa SALES ny
如果员工记录与IT相关而不仅仅是那些应该显示的,如果不是显示SALES,如果不是显示财务。
答案 0 :(得分:2)
你需要选择一个,好像CASE陈述最好:
select name
, max(type) keep (dense_rank first order by priority asc) as type
, max(region) keep (dense_rank first order by priority asc) as region
from ( select a.*
, case type
when 'IT' then 1
when 'SALES' then 2
when 'FINANCE' then 3
end as priority
from my_table a
)
group by name
FIRST
函数根据指定的顺序选择第一个排名值。
答案 1 :(得分:0)
我建议添加一个表来存储TYPES
及其相关的优先级 - 如果在表和类型表之间添加FOREIGN KEY
约束,那么可以断言该类型始终具有优先级
获得优先级的另一种方法是创建一个函数,该函数将类型作为输入并返回优先级。它会提供与表类似的功能,但稍微混淆一些。
除此之外 - 我同意@Ben的分析功能是获得结果的最佳方法。
Oracle 11g R2架构设置:
CREATE TABLE types (
type VARCHAR2(20) PRIMARY KEY,
priority NUMBER(3)
)
/
INSERT INTO types
SELECT 'IT', 1 FROM DUAL
UNION ALL SELECT 'SALES', 2 FROM DUAL
UNION ALL SELECT 'FINANCE', 3 FROM DUAL
UNION ALL SELECT 'MARKETING', NULL FROM DUAL
/
CREATE TABLE minions (
name VARCHAR2(30),
type VARCHAR2(20),
region VARCHAR2(2),
FOREIGN KEY ( type ) REFERENCES types ( type )
)
/
INSERT INTO minions
SELECT 'john', 'IT', 'ny' FROM DUAL
UNION ALL SELECT 'john', 'SALES', 'ny' FROM DUAL
UNION ALL SELECT 'john', 'FINANCE', 'ny' FROM DUAL
UNION ALL SELECT 'john', 'MARKETING', 'ny' FROM DUAL
UNION ALL SELECT 'kevin', 'MARKETING', 'ny' FROM DUAL
UNION ALL SELECT 'lisa', 'SALES', 'ny' FROM DUAL
UNION ALL SELECT 'lisa', 'FINANCE', 'ny' FROM DUAL
/
查询1 :
SELECT name,
MAX( m.type ) KEEP ( DENSE_RANK FIRST ORDER BY priority ) AS type,
MAX( region ) KEEP ( DENSE_RANK FIRST ORDER BY priority ) AS region
FROM minions m
INNER JOIN
types t
ON ( m.type = t.type )
WHERE priority IS NOT NULL
GROUP BY name
ORDER BY name
<强> Results 强>:
| NAME | TYPE | REGION |
|------|-------|--------|
| john | IT | ny |
| lisa | SALES | ny |