0

My current data looks like this

OrderID | Category
1       | A 
1       | A 
1       | B 
1       | B 
1       | D 
2       | B 
3       | B 
3       | B 
3       | B 

What I would like is a kind of pivot, which shows a count of how many times an OrderID is placed in a particular category. The exception is for category 'B'. Every time an OrderID belongs to category B, I would like to display it as an instance of B_x where x is the xth instance of B being called. Therefore OrderID 1 would have B_1 and B_2, OrderID 2 would have just B_1, OrderID 3 would have B_1, B_2 and B_3. Therefore, the final results would be similar to this

OrderID | A | B_1 | B_2 | B_3 | D 
1       | 2 | 1   | 1   | 0   | 1 
2       | 0 | 1   | 0   | 0   | 0 
3       | 0 | 1   | 1   | 1   | 0 

I'm using SQL for this, so any pointers would be greatly appreciated!

Matt
  • 14,906
  • 27
  • 99
  • 149
  • 5
    Is there a bound on how many `B`s you might have to deal with for any given `OrderID`? SQL doesn't do well with a varying number of columns. Also, what actual database system are you using? SQL is the standard database language, but different database systems (e.g. Oracle, mysql, SQL Server) may have different features that help or hinder in producing a solution. – Damien_The_Unbeliever Jul 03 '14 at 12:55
  • Should `OrderID 1` have a value of `1` for column `D` in the results you are wanting? Instead of a `0`. – Linger Jul 03 '14 at 13:01
  • since the column names appear to be a of a variable number, you'll have to use dynamic SQL. Here's an example: http://stackoverflow.com/questions/18317732/sql-server-pivot-table-with-joins-and-dynamic-columns combine this with running totals for count of B to get column names and you should be good. http://stackoverflow.com/questions/860966/calculate-a-running-total-in-sqlserver for running total example. – xQbert Jul 03 '14 at 13:09
  • @Damien_The_Unbeliever: There is no bound on the number of B's – PrasannaKovalam Jul 03 '14 at 15:59
  • @xQbert: Thank you I'll give it a go and possibly post back!! – PrasannaKovalam Jul 03 '14 at 16:01
  • Which DBMS are you using? Postgres? Oracle? –  Dec 01 '14 at 12:22

0 Answers0