计算单行中元素的出现次数

时间:2013-09-18 04:02:41

标签: sql oracle oracle10g

我有一个要求,比如我需要在oracle表的一行中找到特定值的出现次数。

说我的源表看起来像这样,

ID   score1   score2   score3   score4 score5
---------------------------------------------
aa    -1       65       -1       -1      82
bb    -1       65       99       14      82

我需要一个返回结果的查询,如

ID   score1   score2   score3   score4 score5  count ( count of -1 occurences)
------------------------------------------------------
aa    -1       65       -1       -1      82     3
bb    -1       65       99       14      82     1

我使用的oracle版本是Oracle 10g(所以使用PIVOT选项排除了。)任何人都可以帮我解决这个问题。

1 个答案:

答案 0 :(得分:2)

您可以使用CASE或DECODE语句。

select table_name.*,
       case score1 when -1 then 1 else 0 end +
       case score2 when -1 then 1 else 0 end +
       case score3 when -1 then 1 else 0 end +
       case score4 when -1 then 1 else 0 end +
       case score5 when -1 then 1 else 0 end
        as score_count
  from table_name;

示例here