2016-06-01 119 views
0

我創建了一個類似的表格創建了幾個臨時表,並在我的數據庫連接它們:SQL:集團由多列

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 

我該如何做到這一點?

+2

。 。將問題表格作爲文本而不是鏈接來處理會更好。 –

+0

爲什麼'細分客戶數'是以小數爲單位的? – Squirrel

+0

這裏的桌子沒有出現在這裏。細分爲1-10。 –

回答

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