0

次の2つのテーブルがあります。

表 X

Product  Type   Sales
1   a   1
1   b   1
1   c   0
1   a   2

テーブルY

Product Inventory
1   10

クエリが返されることを望みます:

Product type    sales   inventory
1          a    3       10
1          b    1       0
1          c    0       0

問題は集計関数を使用しており、在庫を過大にカウントしていないことです。例:

select X.product, X.type, sum(X.sales), sum( case when X.sales > 0 then Y.inventory else 0 end) 
from x,y
where x.product = y.product 
group by x.product,x.type
4

1 に答える 1

2

に基づいて最終結果を作成している場合sales、次の結果が得られます。

select distinct x1.product,
  x1.type,
  x2.totalsales,
  case when x1.sales > 0 then y.inventory else 0 end
from x x1
left join
(
  select product,
      type,
      sum(sales) as TotalSales
  from x
  group by Product, Type
) x2
  on x1.product = x2.product
  and x1.type = x2.type
left join y
  On Y.Product = x1.Product

デモで SQL Fiddle を参照してください

inventory合計売上高がゼロより大きいのに、サンプル結果にforbがゼロとしてリストされている理由がわかりません。

編集#1

あなたのコメントに基づいて、次の使用を検討することをお勧めしますrow_number()

select product, 
  type,
  totalsales,
  case when rn = 1 then inventory else 0 end inventory
from
(
  select x.product,
    x.type,
    sum(sales) TotalSales,
    row_number() over(partition by x.product order by x.type) rn,
    y.inventory
  from x 
  inner join y
    on x.product = y.product
  group by x.product, x.type, y.inventory
) src

デモで SQL Fiddle を参照してください

または、 でグループ化できない場合inventoryは、サブクエリの外で結合します。

select src.product, 
  src.type,
  src.totalsales,
  case when rn = 1 then inventory else 0 end inventory
from
(
  select x.product,
    x.type,
    sum(sales) TotalSales,
    row_number() over(partition by x.product order by x.type) rn
  from x 
  group by x.product, x.type
) src
inner join y
  on src.product = y.product

デモで SQL Fiddle を参照してください

于 2012-11-23T21:23:54.203 に答える