How do I SUM DISTINCT Rows?

后端 未结 3 1834
误落风尘
误落风尘 2020-12-19 05:51

I\'m struggling with a query where I need to SUM DISTINCT Rows. There has to be a way to do this... but I\'m lost.

Here\'s what I\'ve got:

SELECT D         


        
相关标签:
3条回答
  • 2020-12-19 06:02

    An easy answer is use "group by". Group by has the same effect with the same fields as distinct, but allows you to use aggregate functions. You can add a "Having" clause after the group by to filter what records you would like to see.

    0 讨论(0)
  • 2020-12-19 06:10

    Use GROUP BY along with the SUM() and COUNT() aggregates.

    SELECT count(*) as totalRows, Zipcodes.CountyID,
       sum(us_co_est2005_allData.PopEstimate2005) as SumPopEstimate2005, 
       sum(us_co_est2005_allData.EstimatesBase2000) as SumEstimatesBase2000,
      users_link_territory.userID
    
    FROM
      Zipcodes Inner Join Users_link_territory ON zipcodes.CountyID = 
      Users_link_territory.CountyID Inner Join
      us_co_est2005_alldata ON zipcodes.FIPS = us_co_est2005_alldata.State AND zipcodes.code = us_co_est2005_alldata.County
    
    WHERE (users_link_territory.userid = 4)
    
    GROUP BY  Zipcodes.CountyID,users_link_territory.userID
    

    Depending on your db server, this will be more efficient than doing a sub-select.

    0 讨论(0)
  • 2020-12-19 06:15

    If you just want an overall figure for it try

    select sum(PopEstimate2005), sum(EstimatesBase2000)
    from(
        SELECT  Distinct
            Zipcodes.CountyID, 
            us_co_est2005_allData.PopEstimate2005, 
            us_co_est2005_allData.EstimatesBase2000, 
            users_link_territory.userID 
        FROM 
            Zipcodes Inner Join 
            Users_link_territory ON zipcodes.CountyID = Users_link_territory.CountyID Inner Join 
            us_co_est2005_alldata ON zipcodes.FIPS = us_co_est2005_alldata.State AND zipcodes.code = us_co_est2005_alldata.County 
        WHERE 
            (users_link_territory.userid = 4)
    ) as foo
    
    0 讨论(0)
提交回复
热议问题