2015-02-06 40 views
0

我有這個表如何生成三列數的表格?

|model size color customer| 
|ip4g 8 black Boy | 
|ip4g 8 white Boy | 
|ip4g 16 white Girl | 
|ip4g 16 black Girl | 

我知道如何

Select model, size, color, count(*) from table group by model, size, color; 

我需要的是生成一個Excel表格看起來像這樣來查詢計數。

enter image description here

我不知道我怎麼會能夠生產每客戶是= 0的計數和。

我用所有可能的組合製作了一張桌子。 然後做這個查詢:

select x.model, x.size, x.color, sum(y.customer), count(y.*) 
from table x left join table y on x.model = y.model 
and x.size = y.size and x.color = y.color group by 
x.modelname, x.size, x.color; 

我少於預期的數據。然後,我還需要顯示所有客戶, 和客戶數量可能會有所不同。

請幫忙。謝謝。

回答

1

使用SUM()計算行數爲每一個客戶:

Select model, size, color, 
     SUM(customer = 'Customer 1') AS Customer1, 
     SUM(customer = 'Customer 2') AS Customer2, 
     SUM(customer = 'Customer 3') AS Customer3, 
     SUM(customer = 'Customer 4') AS Customer4, 
     SUM(customer = 'Customer 5') AS Customer5, 
     count(*) AS Total 
from table 
group by model, size, color; 

customer = 'Customer N'1如果客戶匹配,0如果沒有,那麼這將算爲每一個客戶行。

+0

Thanks @Barmar。如果不包括所有客戶,我如何獲得總數?另外,如果客戶數量在任何時候都不一樣呢?先謝謝你。 – 2015-02-06 02:51:20

+0

您需要一個列出所有可能的型號,尺寸和顏色組合的表格。然後,您可以對此查詢使用「LEFT JOIN」爲沒有客戶的組合生成零值。 – Barmar 2015-02-06 02:58:13

+0

您好@barmar,我已經爲可能的組合列表製作了表格,並將其加入。如果客戶數量是動態的,我將如何查詢?有時,我將只有2個客戶,有時候是3. – 2015-02-06 08:27:04