views:

123

answers:

4

I have a table like this:

UserID     Customer ID status        
1               1          1
1               2          1 
1               3          1
1               4          2
1               5          1
1               6          3
1               7          2
2               8          1
2               9          2 
 ........

I want to summarize this table, to this:

 UserID           count(status 1)    count(status 2)   count(status 3)
    1                4                2                     1 
    2                1                2                     3
   .........

How can I do that in PL/SQL?

Thank in advance

+6  A: 

You can group on UserId and sum up the different status codes.

Something like:

select
  UserId,
  sum(case status when 1 then 1 else 0 end) as Status1,
  sum(case status when 2 then 1 else 0 end) as Status2,
  sum(case status when 3 then 1 else 0 end) as Status3
from SomeTable
group by UserId
order by UserId

You might also consider simply grouping on UserId and status, although the result is of course differently laid out:

select UserId, status, count(*)
from SomeTable
group by UserId, status
order by UserId, status
Guffa
when I replace "end case" in first query by "end" (Remove case), the query runs, otherwise it procedures "ORA-00907: missing right parenthesis". Can you explain this?
Vimvq1987
you just shouldn't use `end case` in oracle. use just `end`.
be here now
@Vimvq1987: Obviously the correct syntax is `case ... end`, not `case ... end case`. I checked this page for the syntax, but it's appearently wrong: http://www.oracle.com/technology/sample_code/tech/pl_sql/htdocs/x/Case/start.htm
Guffa
You need `end case` in PL/SQL statements (similar to `end if`, `end loop`), but only `end` in SQL queries, even if they're inside a PL/SQL block.
Alex Poole
+1  A: 
select userid, 
       count(decode(status, 1, 1, null)),
       count(decode(status, 2, 1, null)),
       count(decode(status, 3, 1, null)),
  from table
 group by userid
be here now
+1  A: 
SELECT *
  FROM ( SELECT UserID,
                status,
                COUNT(status)
           FROM <table>
          GROUP BY UserID,
                   status
       )
 PIVOT(COUNT(status) FOR status IN (1,2,3))
Mark Baker
A: 

Just to follow up @Vimvq1987 and @Guffa comments: the correct syntax for SQL is case ... end, but for PL/SQL it sould be case ... end case, so the information on the link you've provided is right.

Hence in your SQL queries (either you execute it in SQL-Plus or in the DML in PL/SQL) you should use case ... end, but in PL/SQL routines case ... end case is required.

andr