我想显示仅剩一项的所有位置。使用SUM函数进行了尝试,但它仍然为我提供了多个具有相同位置的行,其中3个文章的总和为1
SELECT location, artnr, sum(qty)
FROM location_stock
GROUP BY location, artnr
HAVING sum(qty) = 1
结果:
Location Art Nr Sum(Qty)
12345 5345 1
12345 5874 1
12345 4756 1
我想要的是具有一篇文章nr和一份数量的位置:
Location Art Nr Sum(Qty)
12345 5345 1
答案 0 :(得分:0)
您可以使用row_number()
窗口功能
select * from ( SELECT location, artnr, sum(qty) as s,
row_number() over(partition by location order by artnr asc) rn
FROM location_stock
GROUP BY location, artnr
HAVING sum(qty) = 1
) a where a.rn=1
答案 1 :(得分:0)
假设数量永远不会为负或为零,那么这应该起作用:
SELECT location, max(artnr) as artnr, sum(qty)
FROM location_stock
GROUP BY location
HAVING SUM(qty) = 1;
有关更通用的解决方案:
SELECT location, max(artnr) as artnr, sum(qty)
FROM location_stock
GROUP BY location
HAVING MIN(artnr) = MAX(artnr) AND
SUM(qty) = 1;
如果您实际上并不关心数量,而只关心一个artnr
,则删除SUM(qty)
上的条件。