0

我通过创建几个临时表并将它们加入我的数据库中来创建一个类似的表:

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 

我如何实现这一目标?

4

1 回答 1

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
于 2016-06-01T01:39:07.660 回答