怎么写sql查询
好久好久没有碰电脑了……
一个库存表,设有最大库存值和最小库存值。要求找出高于最高库存或者低于最低库存的商品,并说明是高还是低。
表结构:
商品ID,最高库存,最低库存,当前库存
0001 500 200 10000
0002 400 100 2
0003 5000 100 452
……
要求结果:
商品ID,当前库存, 判断类型
0001 10000 高于最大库存
0012 2 低于最小库存
[最优解释]
赶紧结贴了,多给我点分,谢谢
[其他解释]
null
[其他解释]
SELECT 商品ID ,
当前库存 ,
'高于最大库存' 判断类型
FROM TB
WHERE EXISTS ( SELECT 1
FROM TB b
WHERE TB.当前库存 > b.最高库存
AND b.商品id = TB.商品id )
UNION ALL
SELECT 商品ID ,
当前库存 ,
'低于最小库存' 判断类型
FROM TB
WHERE EXISTS ( SELECT 1
FROM TB b
WHERE TB.当前库存 < b.最高库存
AND b.商品id = TB.商品id )
declare @T table
(商品ID varchar(4),最高库存 int,最低库存 int,当前库存 int)
insert into @T
select '0001',500,200,10000 union all
select '0002',400,100,2 union all
select '0003',5000,100,452
select
商品ID,当前库存,
判断类型='高于最大库存'
from @T where 当前库存>最高库存 union all
select
商品ID,当前库存,
判断类型='低于最小库存'
from @T where 当前库存<最低库存
order by 商品ID
/*
商品ID 当前库存 判断类型
---- ----------- ------------
0001 10000 高于最大库存
0002 2 低于最小库存
*/
--创建数据开始
if(object_id('a')is not null) drop table a
go
create table a
(
GoodID varchar(50),
maxstore int,
minstore int,
RealStore int
)
go
insert into a
select '0001',500,200,10000 union all
select '0002',400,100,2 union all
select '0003',5000,100,452
--创建数据结束
--语句
select GoodID,RealStore,case when realStore>maxStore then '高于最大库存' when realStore <minstore then '低于最小库存' else '正常库存'end as judge
from a
--结果展示.
/*
GoodID RealStore judge
-------------------------------------------------- ----------- ------------
0001 10000 高于最大库存
0002 2 低于最小库存
0003 452 正常库存
(3 行受影响)
*/
select 商品ID,当前库存,
(case when 当前库存>最高库存 then '高于最大库存' when 当前库存<最低库存 then '低于最小库存' end)as 判断类型
from tableName
where 当前库存>最高库存 or 当前库存<最低库存
-->测试数据
declare @tableName table(商品ID varchar(5),最高库存 int,
最低库存 int,当前库存 int)
insert into @tableName
select '0001',500,200,10000 union all
select '0002',400,100,2 union all
select '0003',5000,100,452
-->查询语句
select 商品ID,当前库存,
(case when 当前库存>最高库存 then '高于最大库存'
when 当前库存<最低库存 then '低于最小库存'
end)as 判断类型
from @tableName
where 当前库存>最高库存 or 当前库存<最低库存
-->查询结果
商品ID 当前库存 判断类型
----- ----------- ------------
0001 10000 高于最大库存
0002 2 低于最小库存
(2 行受影响)