Sql学习第一天——SQL 练习题(建表/sql语句)

2022-05-24 0 311

题目:来自Madrid且订单数少于3的消费者  

建表:

复制代码 代码如下:

set nocount on –当 SET NOCOUNT 为 ON 时,不返回计数(表示受 Transact-SQL 语句影响的行数)。当 SET NOCOUNT 为 OFF 时,返回计数

use SY

GO

if object_Id(‘dbo.Orders’) is not null

drop table dbo.Orders

GO

if object_Id(‘dbo.Customers’) is not null

drop table dbo.Customers

GO

create table dbo.Customers

(

customerid char(5) not null primary key ,

city varchar(10) not null

);

insert into dbo.Customers values(‘FISSA’,’Madrid’);

insert into dbo.Customers values(‘FRNDO’,’Madrid’);

insert into dbo.Customers values(‘KRLOS’,’Madrid’);

insert into dbo.Customers values(‘MRPHS’,’Zion’);

create table dbo.Orders

(

orderid int not null primary key ,

customerid char(5) null references customers(customerid)

)

insert into dbo.Orders values(1,’FRNDO’);

insert into dbo.Orders values(2,’FRNDO’);

insert into dbo.Orders values(3,’KRLOS’);

insert into dbo.Orders values(4,’KRLOS’);

insert into dbo.Orders values(5,’KRLOS’);

insert into dbo.Orders values(6,’MRPHS’);

insert into dbo.Orders values(7,null);

——————————————————————————————————————————

做题分析:

复制代码 代码如下:

select customerid as 消费者,count(customerid) as 订单数

from dbo.Orders

where customerid in (

select customerid

from dbo.Customers

where city = ‘Madrid’)

group by customerid

having count(customerid) < 3

结果如图所示:

Sql学习第一天——SQL 练习题(建表/sql语句)

–第一次想到的答案,突然发现少了一个来自Madrid的FISSA订单,FISSA订单数量为0,所以在Orders表中没有出现,所以上面的写法会少一个.

–推翻了上面的答案,又想到了用表的连接,而用内连接出现的情况会和上面的一样,所以我选择了左连接,如下:

复制代码 代码如下:

select C.customerid as 消费者,count(O.customerid) as 订单数

from dbo.Customers as C left join dbo.Orders as O on C.customerid = O.customerid

where C.city= ‘Madrid’

group by C.customerid

having count(C.customerid) < 3

结果如图所示:

Sql学习第一天——SQL 练习题(建表/sql语句)

–查询发现是正确的。

–分析查看不带条件的左连接

复制代码 代码如下:

select * from dbo.Customers as C left join dbo.Orders as O on C.customerid = O.customerid


复制代码 代码如下:

select * from dbo.Customers as C left join dbo.Orders as O on C.customerid = O.customerid

结果如图所示:

Sql学习第一天——SQL 练习题(建表/sql语句)

–书中给的标准答案是:

复制代码 代码如下:

select C.customerid , count(O.orderid) as numorders

from dbo.Customers as C left join dbo.Orders as O on C.customerid = O.customerid

where C.city= ‘Madrid’

group by C.customerid

having count(O.orderid) < 3

order by numorders

结果如图所示:

Sql学习第一天——SQL 练习题(建表/sql语句)

书中给的只是多了一个order by 进行定义了排序方式(以numorders这一列的升序进行排序)

免责声明:
1、本网站所有发布的源码、软件和资料均为收集各大资源网站整理而来;仅限用于学习和研究目的,您必须在下载后的24个小时之内,从您的电脑中彻底删除上述内容。 不得使用于非法商业用途,不得违反国家法律。否则后果自负!

2、本站信息来自网络,版权争议与本站无关。一切关于该资源商业行为与www.niceym.com无关。
如果您喜欢该程序,请支持正版源码、软件,购买注册,得到更好的正版服务。
如有侵犯你版权的,请邮件与我们联系处理(邮箱:skknet@qq.com),本站将立即改正。

NICE源码网 MsSql Sql学习第一天——SQL 练习题(建表/sql语句) https://www.niceym.com/61252.html