2010-03-03 100 views
0

我在解决此问题时遇到问题。请帮忙。查询问题 - 结果不正确

我有一个名为Product_Information的表。我想要统计类别和子类别中的产品数量。

这是表

Product_Id - Product_Title - Product_Sub_Category - Product_Category 
1 ----------------abc------------------XYX------------------X 
2 ----------------def------------------XYX------------------Z 
3 ----------------ghi------------------XYX------------------X 
4 ----------------jkl------------------XYM------------------Z 

,我希望得到的结果是一样

result 
------ 

Product_Category-Product_Sub_Category-count(Product_Id) 
X--------------------XYX-------------------------2 
Z--------------------XYX-------------------------1 
Z--------------------XYM-------------------------1 

(对不起,我在一个糟糕的方式呈现信息)

我用下面的查询:

Select 
Product_Category, 
Product_Sub_Category, 
count(`Product_Id`) 
from product_information 
group by 
Product_Category 

但它给了我错误的结果。

+0

你可以编辑你的问题,并提出更好的? – Kangkan 2010-03-03 07:28:07

+0

具体而言,你可以把你的表和查询放在一个代码块中。 – 2010-03-03 07:29:31

+0

你不需要按Product_Category,Product_Sub_Category进行分组,只能在你的问题的代码中按照Product_Category进行分组。 – 2010-03-03 13:29:34

回答

1

如果你只需要在一个特定的子类别的产品数量,然后使用:

select count(*) from Product_Information 
where Product_Category = ? and Product_Sub_Category = ? 

如果你需要为所有这些数字,那么你就需要一群像这样:

select Product_Category, Product_Sub_Category, count(*) 
from Product_Information 
group by Product_Category, Product_Sub_Category; 
+0

问题是,如果我使用查询2,我会得到一个混合结果。 的意思是我看到不属于类别的子类别..好心帮助 – 2010-03-03 13:19:09

1

您可以使用分析函数和分区,也可以分别执行几个查询(如果您愿意,可以将它们组合在一个大型查询中),但以下是基本查询: 按类别计数

Product_Category, count(Product_Id) 

from product_information 

group by Product_Category 

计数由子类别

Product_Category, Product_Sub_Category, count(Product_Id) 

from product_information 

group by Product_Category, Product_Sub_Category 
+0

谢谢人们,我能解决我的问题 – 2010-03-03 13:33:21

0

更改您的查询:选择

 
Product_Category, Product_Sub_Category, count(Product_Id) 

from product_information 

group by Product_Category , Product_Sub_Category ; 

它会给你造成的罚款。