查询主键

时间:2016-05-20 07:34:50

标签: sql oracle11g

请注意以下结果,包含primary key (reg_num)的七列:

reg_num day Morning Midday  Lunch   Evening Total_Period
0983776412  3   Yes Yes No  Yes 3
0985674389  3   No  Yes No  No  1
0983464736  4   Yes No  Yes No  2
0983466827  11  No  No  No  No  0
0983481234  15  Yes Yes Yes Yes 4

每行reg_num显示一天的“是”和“否”组合。您会看到最后一列“Total_Period”是每行中所有“yes”的计数。

请您知道我如何计算“Total_Period”的值?

2 个答案:

答案 0 :(得分:0)

最简单的方法是:

select decode(Morning, 'Yes', 1, 0)  + 
       decode(Midday, 'Yes', 1, 0)   + 
       decode(Lunch, 'Yes', 1, 0)    + 
       decode(Evening , 'Yes', 1, 0) 
from your_table

答案 1 :(得分:0)

如果您的数据库是11G及以上,您也可以尝试ORACLE REGULAR exp。希望它有所帮助。

SELECT a.reg_no,
  a.dy,
  a.morning,
  a.middday,
  a.lunch,
  a.evening,
  REGEXP_COUNT(a.morning
  ||','
  ||a.middday
  ||','
  ||a.lunch
  ||','
  ||a.evening,'Yes') Total_Period
FROM
  (SELECT 0983776412 reg_no,
    3 dy,
    'Yes' AS morning,
    'Yes' AS middday,
    'No' lunch ,
    'Yes' evening,
    NULL AS Total_Period
  FROM dual
  )A;