Skip to content
Advertisement

How to use DISTINCT and SUM in a same SQL query on MS SQL Express

enter image description hereI have a situation where I need to get DISTINCT values from column “note” and then get the SUM of “price” for above records.

I tried with different queries but none of them are working fine.

SELECT    DISTINCT   note ,price( select SUM (price) FROM  [tableName] where Archived ='0'

SELECT    sum(price),(SELECT DISTINCT  note , price from  [tableName] where Archived ='0')

In a nutshell I need to get the sum of prices for the distinct records.

Advertisement

Answer

Maxbe this will be one way to do it:

select distinct sum(price) over(partition by note), note
from tablename
where Archived = 0

Here is a demo on SQLServer

If I have understood you correctly you need distinct note values and only one sum for all of them … then something like this:

select distinct note, (select sum(price) from tablename) sum_tot
from tablename
where Archived = 0

P.S. do add expected result….

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement