AdventureWorks 2008 R2 を使用して、次のグリッドをクエリしたい
- 縦軸にテリトリー・営業担当者の組み合わせを一覧表示
- 横軸に各サブカテゴリをリストします
all the line items
各セルは、そのカテゴリ/テリトリー/販売担当者の組み合わせで2 or more
数量を持つ販売の合計数 (一意の SalesOrderID ) を指定します。
これがサンプルです(作成されたデータ、実際のものを照会する方法がわかりません!):
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