同时查询出最大值与最小值

有个题目针对SQL Server 自带的Northwind数据库提出的,如下:

--->查询表Products中库存量最大和最小的商品信息(商品编号,商品名,库存量)。

Products表结构如下:

CREATE TABLE [dbo].[Products](
 [ProductID] [int] IDENTITY(1,1) NOT NULL,
 [ProductName] [nvarchar](40) NOT NULL,
 [SupplierID] [int] NULL,
 [CategoryID] [int] NULL,
 [QuantityPerUnit] [nvarchar](20) NULL,
 [UnitPrice] [money] NULL,
 [UnitsInStock] [smallint] NULL,
 [UnitsOnOrder] [smallint] NULL,
 [ReorderLevel] [smallint] NULL,
 [Discontinued] [bit] NOT NULL,

考虑这样一个问题,库存量最大的商品或者库存量最小的商品都不止一个,同时取出它们信息,怎么取呢?之前参考(http://database.51cto.com/art/201009/227730.htm)这里的代码,后来经过一哥们提醒,才发现居然给蒙了。好好的union + max + min方法不用,反而去创建几个临时表。妹夫的,看来哥我还真是嫩的。

好,解题代码如下:

select [ProductID] ,[ProductName],[UnitsInStock] 
from [Products] p  where p.[UnitsInStock] = ( select max( [UnitsInStock] ) from [Products] p1)
union all
select [ProductID] ,[ProductName],[UnitsInStock] 
from [Products] p  where p.[UnitsInStock] = ( select min( [UnitsInStock] ) from [Products] p2)

执行结果(我事先多加了一条最大库存量的记录):

 

PS:并且上面使用union all而不union还是有原因的。

union 需要去除重复项记录,而union all直接结合两个数据表,所以union all 的效率是要比union要高得多的。

union all 与union 的区别详情自己去找找。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值