0

AdventureWorks 2008 R2 を使用して、次のグリッドをクエリしたい

  1. 縦軸にテリトリー・営業担当者の組み合わせを一覧表示
  2. 横軸に各サブカテゴリをリストします
  3. 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
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 に答える