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

来源:互联网 发布:4g网络优化先培训骗局 编辑:程序博客网 时间:2024/06/08 06:47

有个题目针对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 allselect [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 的区别详情自己去找找。

原创粉丝点击