Summarize aggregated data

前端 未结 5 1812
挽巷
挽巷 2021-01-13 14:27

I have a table like as follows:

SoftwareName    Count    Country
Project         15       Canada
Visio           12       Canada
Project         10       USA
Visi         


        
相关标签:
5条回答
  • 2021-01-13 14:34

    in SQL 2005 or later there-SQL keyword "Pivot" that does this for you, Check out the following link:

    http://msdn.microsoft.com/en-us/library/ms177410.aspx

    0 讨论(0)
  • 2021-01-13 14:45
    SELECT SoftwareName, 
      SUM( CASE Country WHEN 'Canada' THEN [Count] ELSE 0 END ) AS Canada,
      SUM( CASE Country WHEN 'USA'    THEN [Count] ELSE 0 END ) AS USA,
      SUM( [Count] ) AS Total
    FROM [Table] 
    GROUP BY SoftwareName;
    
    0 讨论(0)
  • 2021-01-13 14:53

    This is called table pivoting. In your simple case, there are just two columns; in general, there could be 200 countries or so, in which case, the pivoting becomes rather hard.

    There are many resources online describing how to do it: Google for 'pivot table sql'.

    0 讨论(0)
  • 2021-01-13 14:56

    OK...Here's how to do it using PIVOT:

    SELECT Softwarename, Canada, USA, Canada + USA As TOTAL from SoftwareDemo 
    PIVOT 
        (
         SUM([Count])
         FOR Country
         IN (Canada, USA)
        ) AS x
    
    
    Softwarename                                       Canada      USA         TOTAL
    -------------------------------------------------- ----------- ----------- -----------
    Project                                            15          10          25
    Visio                                              12          5           17
    
    (2 row(s) affected)
    
    0 讨论(0)
  • 2021-01-13 14:58

    i think you can use this Link :

    Sum of unique records - better performance than a cursor

    and i think using PIVOT Function have a best performance rater SUM() function.!

    0 讨论(0)
提交回复
热议问题