SQL聚合/查找值问题并防止过度计数

时间:2012-11-23 21:05:11

标签: sql sql-server

我有以下两个表:

表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

1 个答案:

答案 0 :(得分: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 with Demo

我不确定为什么您的样本结果中inventory b列为零,因为它的总销售额大于零。

编辑#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 with Demo

或者,如果您不能按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 with Demo