Search code examples
sqlsumdistinctsql-server-2008r2-express

How to run distinct and Sum in one query in sql server 2008 R2


I have a table #1 as shown in image attached. First i want to sum all quantity of all distinct id. Then want to show number of id that have same quantity.

enter image description here


Solution

  • Try this one after creating a temporary table

    create table #Temp
    (
      id int, 
      qty int
    )
    
    Insert Into #Temp
    SELECT  id, SUM(qty)
            FROM yourTable
            group by id
    
    SELECT  * FROM #Temp
    
    SELECT  Count(id) , qty
            FROM #Temp
            GROUP BY qty
            ORDER BY qty DESC