显示具有相应列随机3值的不同列值

时间:2016-10-27 19:27:29

标签: sql oracle

我有一个包含列的表员工(state_cd,emp_id,emp_name,ai_cd)如何使用ai_cd中的3个不同值显示disticnt state_cd

答案应该是

state_cd  ai_cd
-------  --------
TX          1
            2
            5
CA          9
            10
            11

2 个答案:

答案 0 :(得分:2)

通常在应用程序中更好地完成此类操作。但是,如果您真的想要,可以在查询中执行此操作:

select (case when row_number() over (partition by state_cd order by ai_cd) = 1
             then state_cd
        end) as state_cd,
       ai_cd
from employee e
order by e.state_cd, e.ai_cd;

order by非常重要,因为SQL结果集是无序的。您的结果需要订购以便有意义。

答案 1 :(得分:0)

只需按state_id分组,然后使用count(Distinct column_name _)

进行计数
select state_id from (select state_id,COUNT(DISTINCT ai_cd) as cnt  from employee  group by state_id) where cnt==3
相关问题