选择大于0的值(如果存在),如果它是唯一选项,则保留0

时间:2017-03-01 14:40:28

标签: sql-server sql-server-2008

编辑: 我为第一次以错误的方式表达我的问题而道歉...我希望这个会更清楚:

我在数据库中查询他可能有数量的所有可能位置上某个项目的数量(在我的情况下是item_id = 321)。

我得到以下结果:

item_location_id    item_def_loc_name   qty_per_location    item_id
8                   A08                 0.00                321                     
962                 POL_113             30.00               321         
5                   A05                 60.00               321

从这三个给定的结果(在某些情况下可能或多或少),我们有一行包含零数量结果,而另一行包含更多数量 - 我的目标是第一个“qty_per_location”大于零但是更小而不是下一个数量(在这个例子中它是30)。

但是对于只分配了一个位置的其他项目,查询将只返回一个qty_per_location = 0的结果行 - 我需要显示它,因为没有更大的数量。

因此,如果我有当前商品的三个库存数量,如下例所示,那么qty = 30的那个将是所需的数量。但是如果我只有一个0位数的位置 - 那么我应该得到零。

enter image description here

嗨再一次 - 我最后做了一些摆弄,并最终将其作为一种可能的解决方案:

DECLARE @QTY as decimal(5,2);

SELECT @QTY = (SELECT SUM(qty_per_location)
FROM [asm].[dbo].[mdta_item-item_def_loc]
where item_id = 321
group by item_id)

SELECT CASE (@QTY) WHEN 0 THEN

(Select top 1 IsNull(qty_per_location, 0) as qty
from [asm].[dbo].[mdta_item-item_def_loc]  -- change this to your table name 
Where qty_per_location = 0 and item_id = 321
Order by qty_per_location)

ELSE 

(Select top 1 IsNull(qty_per_location, 0) as qty
from [asm].[dbo].[mdta_item-item_def_loc]  -- change this to your table name 
Where qty_per_location > 0 and item_id = 321
Order by qty_per_location)

END

但是,这个脚本的问题在于我无法将[qty_per_location]显示为qty结果上方的标题/列名称 - 我得到“(No column name)”。此外,我无法将[item_location_id]列显示在[qty_per_location]旁边......

请分享您的想法。 谢谢大家!

2 个答案:

答案 0 :(得分:1)

此查询将返回表中的第一个数量值,如果表中没有任何具有正值的行,则返回0:

Select IsNull(firstQty.qty_per_location, 0) as qty_per_location,
       tbl.item_location_id
from mdta_item-item_def_loc  tbl  
    left outer join (
        select top 1 tbl2.item_id, tbl2.qty_per_location, tbl2.item_location_id
        from mdta_item-item_def_loc  tbl2  
        Where tbl2.qty_per_location > 0 and tbl2.item_id = 321
        Order by tbl2.qty_per_location
    ) firstQty on tbl.item_id = firstQty.item_id and tbl.item_location_id = firstQty.item_location_id
Where tbl.item_id = 321

如果您对 qty_per_location 的查询进行排序,您也可以获得最低或最高值。

答案 1 :(得分:0)

我要感谢所有善意的人,通过花时间指导我的方式帮助我解决了我的这个SQL难题:)

这是我采用并最终使用的,满足了我的要求:

DECLARE @QTY as decimal(5,2);
SET @QTY = 0;   

IF @QTY < (SELECT SUM(qty_per_location)
FROM [asm].[dbo].[mdta_item-item_def_loc]
where item_id = 321
group by item_id)

Select top 1 qty_per_location, [item_def_loc_name]
from [dbo].[mdta_item-item_def_loc] 

inner join [dbo].[mdta_item_def_loc] on
[dbo].[mdta_item_def_loc].[item_def_loc_id] = [dbo].[mdta_item-item_def_loc].[item_location_id]

where item_id = 321 
order by qty_per_location desc

ELSE

Select top 1 qty_per_location, [item_def_loc_name]
from [dbo].[mdta_item-item_def_loc] 

inner join [dbo].[mdta_item_def_loc] on
[dbo].[mdta_item_def_loc].[item_def_loc_id] = [dbo].[mdta_item-item_def_loc].[item_location_id]

where item_id = 321

祝你们好!

相关问题