1

I have many rows with the fields name, unit, amount. The rows could be

name, unit, amount
========
Some name, A, 100
Some name, B, 300
Another name, A, 400

I want to select all the rows but grouped by name.

The unit can be either A or B. I want an output as:

name, A_amount, B_amount
============
Some name, 100, 300
Another name, 400, 0

So depending on the unit the amount should either be in A_amount or B_amount.

user272735
  • 10,473
  • 9
  • 65
  • 96
Jamgreen
  • 10,329
  • 29
  • 113
  • 224
  • 1
    what you want is a pivot table, there are a lot example on SO. The Solution is also depending on your oracle version. Have a look here: http://stackoverflow.com/questions/4841718/oracle-sql-pivot-query – deterministicFail Aug 20 '14 at 06:41

2 Answers2

2

You need a pivot operation on your base table to achieve this result.

SELECT *
FROM (SELECT name, unit, amount FROM   table1)
PIVOT (amount AS amount FOR (unit) IN ('A' AS a, 'B' AS b))
ORDER BY name;

This query should work for you. Refer this tutorial to learn more about pivot operations.

CodeNewbie
  • 2,003
  • 16
  • 29
0

Can you try the following query

/For query 1/

      Select * from #tblsample A
      inner join #tblsample2 B
       On A.ProductId=B.ProductId

/FOR QUERY 2/

        select * from #tblsample
         except
        select * from #tblsample2

/alternate way for query 2/

          select * from #tblsample
          where productid NOT IN(
          select * from #tblsample2)