简体   繁体   中英

Group by in Oracle SQL

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.

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM