0

使用 AdventureWorks 2008 R2,我想查询一个网格

  1. 在纵轴上列出每个区域/销售人员组合
  2. 在水平轴上列出每个子类别
  3. all the line items每个单元格指定在该类别/地区/销售人员组合中具有2 or more数量的销售总数(唯一 SalesOrderID s)

这是一个示例(虚构的数据,我不知道如何查询真实的东西!):

                         M.Bikes     Chains     Gloves
Northwest   John Doe     15          4          3
Canada      John Doe     4           2          1
Northwest   Jill Doe     0           5          3
Canada      Jill Doe     1           5          1
etc

我认为下面的 SQL 将为我提供山地自行车(subcat id 1),但我不知道如何轻松添加更多列。如果我开始对每一列进行独立查询,它会变得非常慢,非常快(尤其是当我必须将所有这些列重新连接在一起时!)

select
    terr.Name as Territory,
    sp.BusinessEntityID,
    SUM(case when detail.OrderQty > 1 then 1 else 0 end) as MatchingSales

from
    sales.salesorderdetail detail
    inner join sales.SalesOrderHeader header on header.SalesOrderID = detail.SalesOrderID
    inner join sales.SalesPerson sp on sp.BusinessEntityID = header.SalesPersonID
    inner join sales.SalesTerritory terr on terr.TerritoryID = sp.TerritoryID
    inner join sales.SpecialOfferProduct sop on sop.ProductID = detail.ProductID
    inner join Production.Product on Product.ProductID = sop.ProductID
    inner join Production.ProductSubcategory subcat on subcat.ProductSubcategoryID = Product.ProductSubcategoryID

where
    subcat.ProductSubcategoryID = 1 --mountain bikes
4

1 回答 1

1

我想先说我没有安装 AdventureWorks,所以我无法检查查询...我也不知道销售人员姓名列的名称,所以您很可能不得不更改它,但是在这里,您只需在每个子类别的顶部添加一列。我还假设原始查询是正确的。

select
terr.Name as Territory,
sp.Name SalesPerson,
SUM(case when detail.OrderQty > 1 and subcat.ProductSubcategoryID = 1 then 1 else 0 end) as MBikes,
SUM(case when detail.OrderQty > 1 and subcat.ProductSubcategoryID = 2 then 1 else 0 end) as Chains,
SUM(case when detail.OrderQty > 1 and subcat.ProductSubcategoryID = 3 then 1 else 0 end) as Gloves
from
sales.salesorderdetail detail
inner join sales.SalesOrderHeader header on header.SalesOrderID = detail.SalesOrderID
inner join sales.SalesPerson sp on sp.BusinessEntityID = header.SalesPersonID
inner join sales.SalesTerritory terr on terr.TerritoryID = sp.TerritoryID
inner join sales.SpecialOfferProduct sop on sop.ProductID = detail.ProductID
inner join Production.Product on Product.ProductID = sop.ProductID
inner join Production.ProductSubcategory subcat on subcat.ProductSubcategoryID = Product.ProductSubcategoryID
group by terr.Name, sp.Name
于 2013-02-12T02:52:04.793 回答