SQL:按多列分组

时间:2016-06-01 01:32:04

标签: sql sql-server group-by partition-by

我创建了一个类似于此的表,方法是创建几个临时表并将它们连接到我的数据库中:

customerid  Segment Sales   Country
1           1       $3      US
2           2       $4      CAN
3           3       $5      US 
4           5       $6      CAN
5           4       $5      US
6           6       $1      CAN
7           7       $4      US
8           3       $2      CAN
9           2       $2      US
10          1       $1      CAN
11          9       $5      US
12          10      $2      CAN
13          1       $4      US
14          3       $2      CAN
15          4       $1      US

我想要实现的目标是:

Country Segment Count of customer by segment    sum of sales by segment
CAN     1       70                              $3,000 
CAN     2       30                              $3,000 
CAN     3       20                              $3,000 
CAN     4       110                             $3,000 
CAN     5       90                              $3,000 
CAN     6       10                              $3,000 
CAN     7       60                              $3,000 
CAN     8       5000                            $3,000 
CAN     9       2527.857143                     $3,000 
CAN     10      2939.880952                     $3,000 
US      1       3351.904762                     $3,000 
US      2       3763.928571                     $3,000 
US      3       4175.952381                     $3,000 
US      4       4587.97619                      $3,000 
US      5       5000                            $3,000 
US      6       5412.02381                      $3,000 
US      7       5824.047619                     $3,000 
US      8       6236.071429                     $3,000 
US      9       6648.095238                     $3,000 
US      10      7060.119048                     $3,000 

我如何实现这一目标?

1 个答案:

答案 0 :(得分:0)

如果要保留原始表中的所有记录,同时还显示一些聚合,则分区将非常有用。但是,根据您向我们展示的内容,您似乎想要一个结果集,其中每个Country / Segment出现一次。在这种情况下,简单的GROUP BY应该有效:

SELECT Country, Segment, COUNT(*) AS `Count of customer by segment`,
    SUM(Sales) AS `sum of sales by segment`
FROM yourTable
GROUP BY Country, Segment
ORDER BY Country, Segment