我的任务是创建一个SQL查询,它做了几件事情,并且作为SQL的相对新用户,我希望这里的社区能够提供帮助--我不一定需要直接的答案,而是帮助我应该寻找什么才能得到正确的答案!我有三张主桌:
Table 1 = Area
Table 2 = Product_Category
Table 3 = Product_Attributes我想对product_categories的数量做一个计数,以及Product_Attributes中的条目的和,首先按区域分组,然后是Product_Category,例如。
Area1, ProductCat1, Product_attribute1
Area1, ProductCat2, Product_attribute1
Area1, ProductCat2, Product_attribute2
Area1, ProductCat2, Product_attribute3
Area2, ProductCat1, Product_attribute1
Area2, ProductCat1, Product_attribute2
Area3, ProductCat1, Product_attribute8
Area3, ProductCat2, Product_attribute7
Area3, ProductCat3, Product_attribute3应该给我这样的东西:
Area | productCat | NoOfProductCat | NoOfAttribs
Area1 | ProductCat1 | 1 | 1
Area1 | ProductCat2 | 1 | 3
Area2 | ProductCat1 | 1 | 2
Area3 | ProductCat1 | 1 | 1
Area3 | ProductCat2 | 1 | 1
Area3 | ProductCat3 | 1 | 1我的第二个挑战是,
我想显示noofattrib与noofproductcat字段的(十进制)比率。
我的第三个,也是最后一个挑战(让我知道我是否应该把它分成几个独立的问题)--我的一些attrib是年龄--我想对它们进行分组(同样),例如,30天以下的任何一组都被标记为本月的分组,第二组的标记是基于超过30天的任何一个(为了便于参考,我将使用上面的表格,并将日期称为expdate1 ( 30天以下)或expdate2 (超过30天):
Area1, ProductCat1, Product_attribute1, expdate1
Area1, ProductCat2, Product_attribute1, expdate2
Area1, ProductCat2, Product_attribute2, expdate1
Area1, ProductCat2, Product_attribute3, expdate1
Area2, ProductCat1, Product_attribute1, expdate2
Area2, ProductCat1, Product_attribute2, expdate1
Area3, ProductCat1, Product_attribute8, expdate2
Area3, ProductCat2, Product_attribute7, expdate1
Area3, ProductCat3, Product_attribute3, expdate1应给予:
Area | productCat | NoOfProductCat | NoOfAttribs | expdate1 | expdate2
Area1 | ProductCat1 | 1 | 1 | 1 | 0
Area1 | ProductCat2 | 1 | 3 | 2 | 1
Area2 | ProductCat1 | 1 | 2 | 1 | 1
Area3 | ProductCat1 | 1 | 1 | 0 | 1
Area3 | ProductCat2 | 1 | 1 | 1 | 0
Area3 | ProductCat3 | 1 | 1 | 1 | 0这有意义吗?
谢谢你的帮助!
发布于 2015-07-01 00:39:40
您要做的是使用一些case语句按组、聚合和聚合进行分组。就像这样:
SELECT Area,
ProductCat,
1 AS NoOfProductCat, --It's always 1. Dont know what you want here...
COUNT(Product_Attribute) AS NoOfAttribs,
SUM(CASE WHEN Product_Attribue <= 30 THEN 1 ELSE 0 END) AS expdate1, --not really sure what your data looks like here
SUM(CASE WHEN Product_Attribue > 30 THEN 1 ELSE 0 END) AS expdate2
FROM yourTable --your joined table
GROUP BY Area,ProductCathttps://stackoverflow.com/questions/31148954
复制相似问题