Sum Decode statement SQL

时间:2015-10-29 15:49:20

标签: sql oracle group-by

I am trying to sum a few Decode statements and column names, but am having difficulties.

currently it is showing as

 rank | name | points
----------------------
  0   | john |   0
  0   | john |  40
  1   | john |  30
  2   | tom  |  22
  0   | tom  |   0

I expect to have this result:

 rank | name | points
----------------------
  1   | john |  70
  2   | tom  |  22

Query:

Select Rank, Name, Code, Points
  From
   (select 
        decode(Table.name, 'condition1', Table.value) As Points,
        decode(Table.name, 'Condition2', Table.value) As Rank,
        Employee.name as Name,
        Employee.GA1 as Code
      from Table
      inner Join Employee
         on Empolyee.positionseq = name.positionseq
      where Table.name IN ('Condition1', 'Condition2')
    );

2 个答案:

答案 0 :(得分:1)

Select MAX(Rank), Name, Code, SUM(Points)
From
(select 
  decode(Table.name, 'condition1', Table.value) As Points
  decode(Table.name, 'Condition2', Table.value) As Rank
  ,Employee.name as Name
  ,Employee.GA1 as Code
from Table
inner Join Employee
on Employee.positionseq = name.positionseq
where Table.name IN( 'Condition1', 'Condition2'))
GROUP BY Employee.id;

I added the SUM, MAX (for rank) and GROUP BY statements. Also corrected some misspellings (Empolyee)

答案 1 :(得分:0)

我可能会错误地理解您的问题,但是,您似乎正在尝试执行以下操作(为简单起见省略内部联接):

Select MAX(rank), name, SUM(points)
FROM UserRanks
GROUP BY name

根据您上面的数据集,您应该得到以下结果:

rank name  points

1   john  70
2   tom   22