06_27(数据库的查询)

select

use Sales
--select,查询员工表中所有员工的姓名和电话
--select用于指定要返回的列
select 姓名,电话 from Employees
--“*”,返回所有列值
select * from Employees
--distinct关键字消除重复记录
select distinct 生产厂商 from Goods
--top n指定返回查询结果的前几行
select top 4 商品名称,进货价,数量 from Goods
--列别名改变查询结果中的列名
select 编号 as number,姓名 as name,电话 as telephone from Employees
--列表达式
select 商品名称,进货价*数量 as 总金额 from Goods

from子句

select 姓名,电话 from Employees as c where c.姓名='王峰'

where子句

(char,datetime时间,用单引号)

select * from Goods where 商品名称='笔记本电脑'
select 商品编号,数量,售出时间 from Sell where 售出时间<'2005-1-1'
select 商品名称 from Goods where 进货价*数量<10000
select 商品名称 from Goods where 进货时间<'2005-1-1' and 进货价>1000
select * from Employees where 姓名 like '李%'

between关键字

select 商品名称,零售价 from Goods where 零售价 between 2000 and 3000

in关键字

select 商品名称,进货价 from Goods
where 商品名称 in ('打印机','摄像机')

null关键字

select * from Employees where 电话 is not null

order by句子

(用于按查询结果中的一列或多列对查询结果进行排序)

select 商品名称,进货价 from Goods order by 进货价 desc--结果按降序排序
--按数量的升序排序,在数量相同时,再按进货价的降序排列(asc升序排列,系统默认)
select 商品名称,进货价,数量 from Goods order by 3,2 desc

into子句

(用于把查询结果放到一个新建的表中)

select top 15 percent 商品名称,进货价*数量 as 总金额 into 金额表 from Goods
drop table 金额表
select * from 金额表

聚合函数

(对整个表或者列组进行汇总、计算、求平均值或总和)

select COUNT(*) as 人数 from Employees where 部门='财务部'
select '1301' as 员工编号, SUM(数量) as 销售总数量,MAX(数量) as 最大一次销售量
from Sell where 售货员工编号='1301'

group by子句

(对查询结果进行分组)

select 部门,COUNT(*) as 人数 from Employees group by 部门
select 性别,部门,COUNT(部门) as 人数 from Employees group by 性别,部门

with cube汇总

(除了返回group by分租的行外,还包括汇总行)

select 性别,部门,COUNT(部门) as 人数
from Employees group by 性别,部门 with cube

with rollup汇总

(与cube不同的是,rollup只返回第一个分租列的汇总数据)
select 性别,部门,COUNT(部门) as 人数
from Employees group by 性别,部门 with rollup

having子句

(和where相似,where用于表和视图,having用于分组)

select 性别,部门,COUNT(部门) as 人数
from Employees group by 性别,部门 having 性别='1'

多表连接查询

内连接

(返回参与连接查询表中所有匹配的行)

select 销售编号,商品名称, sell.数量 as 销售数量
from Goods,Sell
where Goods.商品编号=Sell.商品编号

左外连接

(以左表为基准表,来找右表)

select 销售编号,商品名称, sell.数量 as 销售数量
from Goods,Sell
where Goods.商品编号*=Sell.商品编号

右外连接

select 销售编号,商品名称,Sell.数量 as 销售数量
from Goods right join Sell
on Goods.商品编号=Sell.商品编号

完全外部连接

(左、右外联接,结果叠加,去掉重复部分)

select 销售编号,商品名称, Sell.数量 as 销售数量
from Goods full join Sell
on Goods.商品编号=Sell.商品编号

交叉连接

(返回两个表交叉查询的结果)

select 销售编号,商品名称,Sell.数量 as 销售数量
from Goods cross join Sell

嵌套查询

select * from Employees
where 编号=any (select 进货员工编号 from Goods)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值