记录中不同列的计数

时间:2017-05-09 07:13:03

标签: sql oracle

如何计算记录的不同列值

  C1   C2     C3    C4
  1  USER1  USER2  USER3
  2  USER1  USER1  USER2
  3  USER2  USER3  USER3
  4  USER1  USER1  USER1 

输出:

 C1   COUNT
  1     3
  2     2 
  3     2
  4     1

如何计算每条记录中的不同用户数。除了比较列值之外,还有其他方法。

感谢。

3 个答案:

答案 0 :(得分:4)

一种方法是unpivot

select c1, count(distinct col) as cnt from (
    select * from your_table
    unpivot( col for lst in(C2, C3, C4) )
) tt
group by c1

答案 1 :(得分:3)

只有三个比较列,这是最简单的方法:

with cte as (
    select c1, c2 from your_table
    union
    select c1, c3 from your_table
    union   
    select c1, c4 from your_table
)
select c1, count(c2) as cnt
from cte
group by c1
/

union运算符生成一个不同的集合,该集合将输入到聚合计数中。

答案 2 :(得分:0)

with cte as (
    select c1, c2 from your_table
    union all
    select c1, c3 from your_table
    union all  
    select c1, c4 from your_table
)
select c1, count(c2) as cnt,count(distinct c2) as distinct_cnt
from cte
group by c1
/