Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to sum distinct values SQL

I'm having trouble coming up with a value for a cell in SSRS, which should be a sum of distinct values. I have a SSRS report that looks similar to the below screenshot:

enter image description here

I'm having trouble getting the value in red ($11.25). I basically need to sum the Ship Cost, based on distinct Tracking #s. So there are two distinct tracking #s, one with a Ship Cost of $5.25 and the other $6.00, so the total displayed in red should be $11.25. But I cannot achieve this in SSRS and can't figure it out in the SQL query either.

I'm thinking a subquery like (and I know the below is not valid SQL):

(SELECT SUM([Ship Cost]) WHERE [Tracking #] IS DISTINCT) AS [Ship Cost]

But I don't know how to write it.

like image 904
kyle_13 Avatar asked Aug 13 '13 19:08

kyle_13


People also ask

How do you find total distinct records?

To count the number of different values that are stored in a given column, you simply need to designate the column you pass in to the COUNT function as DISTINCT . When given a column, COUNT returns the number of values in that column. Combining this with DISTINCT returns only the number of unique (and non-NULL) values.

How do I SUM values from different columns in SQL?

If you need to add a group of numbers in your table you can use the SUM function in SQL. This is the basic syntax: SELECT SUM(column_name) FROM table_name; If you need to arrange the data into groups, then you can use the GROUP BY clause.

Can we use aggregate function with distinct?

Using DISTINCT in aggregationsYou can use DISTINCT when performing an aggregation. You'll probably use it most commonly with the COUNT function. In this case, you should run the query below that counts the unique values in the month column.

How do I SUM values in SQL?

The SUM() function returns the total sum of a numeric column.


2 Answers

Get the distinct list first...

SELECT SUM(SQ.COST)
FROM
(SELECT DISTINCT [Tracking #] as TRACK,[Ship Cost] as COST FROM YourTable) SQ
like image 92
Declan_K Avatar answered Oct 05 '22 22:10

Declan_K


You can do the following:

SELECT SUM(distinct [Ship Cost]) . . .

But, I don't recommend this. You could have two items with the same cost and only one would be counted.

The better way is to select one value for each Tracking #, using the row_number() function:

select SUM(case when seqnum = 1 then [Ship Cost] end)
from (select t.*,
             row_number() over (partition by [Order #], [Tracking #]
                                order by (select NULL)
                               ) as seqnum
      . . .
     ) t
like image 26
Gordon Linoff Avatar answered Oct 06 '22 00:10

Gordon Linoff