SQL 分组(多个)

SQL Grouping (multiple)

我的任务是创建一个 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

我的第二个挑战是,

我想显示 noofattribs 与 noofproductcat 字段的(十进制)比率。

我的第三个也是最后一个挑战(让我知道我是否应该将其分成单独的问题)-我的一些属性是年龄-我想(再次)过滤它们,以便任何在例如,30 天被标记为本月分组,第二个分组基于任何超过 30 天的分组(为了便于参考,我将使用上面的表格,并将日期称为 expdate1 为 under 30天或超过 30 天的 expdate2):

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

这有意义吗?

感谢您的帮助!

您要做的是分组依据、聚合,并使用一些 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,ProductCat