Sql进行泛型查询以获得结果表

时间:2018-04-10 16:34:24

标签: sql

我有以下名为tblItemLocations的表。

 locationName   pickRouteOrder  ispickable  itemnumber
    Loc1             124              1           10-001
    Loc2             126              0           10-001
    Loc3             128              1           10-002
    Loc4             130              0           10-004
    Loc44            136              0           10-004
    Loc5             131              1           10-007
    Loc6             133              1           10-008

需要的结果: Foreach itemnumber,应该只有一个ispickable = 1的记录。 如果Ispickable = 0,则显示No Loc。 记录总数也等于不同项目编号的总数。 例如,在上表中,有5个不同的项目编号(10-001,10-002,10-004,10-007,10-008)。 所以结果表中应该有5条记录。

Resultant table : 
locationName    pickRouteOrder      itemnumber
Loc1             124                  10-001
Loc3             128                  10-002
No Loc           130                  10-004
Loc5             131                  10-007
Loc6             133                  10-008

你能帮忙进行查询以获得结果表吗?

2 个答案:

答案 0 :(得分:3)

试试这个(使用sql-sever和mysql测试):

select 
coalesce( max(case when ispickable = 1 then locationName
                   else null end ), 'no loc') as locationName, 
min( pickRouteOrder ) pickRouteOrder, 
itemnumber
from test 
group by itemnumber

当项目有多个记录且具有最小pickRouteOrder的记录不可选择时(ispickable = 0),上述内容不会生成预期输出。 请尝试下面的内容(修改自Gordon Linoff的答案):

select locationName, pickRouteOrder, itemnumber
from test
where ispickable = 1
union all 
select 'no loc', min(pickRouteOrder), itemnumber -- use group by to eliminate multiple non-pickable records
from test t
where ispickable = 0 and 
      not exists (select 1 from test t2 where t2.itemnumber = t.itemnumber 
                  and t2.ispickable = 1)
group by itemnumber;

答案 1 :(得分:0)

如果最多一行是可选择的和不可删除的(与样本数据一样),您也可以将其视为:

select locationName, pickRouteOrder, itemnumber
from t
where ispickable = 1
union all
select 'no loc', pickRouteOrder, itemnumber
from t
where ispickable = 0 and 
      not exists (select 1 from t t2 where t2.itemnumber = t.itemnumber and t2.ispackable = 1);

在许多情况下,这将比聚合解决方案更快,尽管我也喜欢该版本。

相关问题