子查询的注意事项

任何允许适用表达式的地方都可以适用子查询

嵌套在select语句中的子查询

语法:select(子查询)from表名

嵌套在from语句中的子查询

语法:select...from (子查询) as 表的别名

例子

use E_Market
go
--[1]子查询作为列值来使用
select * from CommoditySort where SortId=1
--查询类别编号为1的商品的名称及类别名称
select CommodityName as 商品名称,
(
select SortName from CommoditySort where SortId=1
) as 类别名称
from CommodityInfo
where SortId=1

--【2】将子查询作为from子句中的表来使用
--查询商品信息表中每种类别商品的库存量是多少
select SOrtId, SUM(Amount) as cnt from CommodityInfo
group by SortId
having SUM(Amount) > 10000
--将上面的查询作为表来使用
select S.SortName as 类别名称, T.cnt as 库存量 from CommoditySort as S
inner join (select SortId,SUM(Amount) as cnt from CommodityInfo
group by SortId
having SUM(Amount) > 10000) as T
on S.SortId=T.SortId

猜你喜欢

转载自www.cnblogs.com/zhangxudong-cnblogs/p/10859698.html