实验案例一:使用函数查询统计信息
实验环境
BDON公司有一台已经安装了SQL Server 2016的服务器,bdqn 数据库中包含products表,表中内容如图4.22所示。
需求描述
1,查询出厂日期晚于2017年5月15日的水果信息
2,分组查询所有水果、蔬菜.坚果的总成本。
3,查询所有水果的名称和出厂日期,以特定格式拼接字符串,如“西瓜的出厂日期是:2017/05/06".
4,查询所有蔬菜的平均成本。
创建表
创建表的代码
create table shuiguo
(
编号 int identity (1,1) primary key,
名称 nvarchar(50) not null,
种类 nvarchar(50) not null,
成本 money not null,
出厂日期 datetime not null,
)
select * from shuiguo
insert into shuiguo (名称,种类,成本,出厂日期)
values ('西瓜','水果','4.100','2017-05-06'),
('芹菜','蔬菜','1.00','2017-04-01'),
('番茄','蔬菜','2.900','2017-05-09'),
('黄瓜','蔬菜','2.200','2017-05-05'),
('香蕉','水果','6.100','2017-05-23'),
('核桃','坚果','28.500','2017-06-02'),
('开心果','坚果','38.110','2017-06-21'),
('蓝莓','水果','50.200','2017-05-15')
查询出厂日期晚于2017年5月15日的水果信息
select * from shuiguo where 出厂日期<'2017-05-15' and 种类='水果'
方法二
select * from products
where 种类 = '水果' and 出厂日期 >= '2017-05-15'
2,分组查询所有水果、蔬菜.坚果的总成本。
select 种类,
sum(成本) as 总成本
from shuiguo
group by 种类
3,查询所有水果的名称和出厂日期,以特定格式拼接字符串,如“西瓜的出厂日期是:2017/05/06".
select 名称 +'的出厂日期是:'+REPLACE(CAST(出厂日期 as varchar(10)),'-''/')
from shuiguo
where 种类='水果'
方法二
select 名称+'的出厂日期是:'+replace(cast(出厂日期 as varchar(10)),'-','/')
from products
where 种类 = ‘水果’
4,查询所有蔬菜的平均成本。
select 种类,avg(成本) as 平均成本 from shuiguo
having 种类='蔬菜'
方法二
select avg(成本) as 平均成本
from products
where 种类=‘蔬菜’
group by 种类