2015-02-06 39 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