Trying to sum distinct values SQL

江枫思渺然 提交于 2019-12-22 04:51:03

问题


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:

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.


回答1:


Get the distinct list first...

SELECT SUM(SQ.COST)
FROM
(SELECT DISTINCT [Tracking #] as TRACK,[Ship Cost] as COST FROM YourTable) SQ



回答2:


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



回答3:


try something like


select sum(shipcost) from
(select distinct tracking#, shipcost from table)

cheers



来源:https://stackoverflow.com/questions/18218108/trying-to-sum-distinct-values-sql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!