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

SQL聚合/查找值出现问题并防止过度计数,sql,sql-server,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 问题是使用聚合函数,而不是过度计算库存。

我有以下两个表格:

表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
如果您是根据
销售
得出最终结果,则应给出以下结果:

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

考虑到
b
的总销售额大于零,我不确定为什么您的样本结果中将
库存
列为零

编辑#1

根据您的意见,我建议您使用
行号()

或者,如果无法按
库存
分组,则在子查询之外加入:

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

参见

此数据的含义是什么?产品类型不同吗?一个产品可以有不同的类型(功能/选项),但它是库存中的产品。感谢您的快速回复。问题是库存是在产品级别(不是类型),我希望它在输出中显示一次,在第一行(或同一产品的任何行,但仅显示一次)。@DimitriKaspersky您使用的是什么关系数据库?mysql、sql server、oracle?@DimitriKaspersky很乐意帮忙,如果这个答案有用,请务必通过左边的复选标记接受它。这将有助于未来的访客,并让你从接受中获得声誉。
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