题目:来自Madrid且订单数少于3的消费者 建表:复制代码代码如下:setnocounton--当SETNOCOUNT为ON时,不返回计数(表示受Transact-SQL语句影响的行数)。当SETNOCOUNT为OFF时,返回计数useSYGOifobject_Id('dbo.Orders')isnotnulldroptabledbo.OrdersGOifobject_Id('dbo.Customers')isnotnulldroptabledbo.CustomersGOcreatetabledbo.Customers(customeridchar(5)notnullprimarykey,cityvarchar(10)notnull);insertintodbo.Customersvalues('FISSA','Madrid');insertintodbo.Customersvalues('FRNDO','Madrid');insertintodbo.Customersvalues('KRLOS','Madrid');insertintodbo.Customer
题目:来自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
结果如图所示:
--第一次想到的答案,突然发现少了一个来自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
结果如图所示:
--查询发现是正确的。
--分析查看不带条件的左连接
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
结果如图所示:
--书中给的标准答案是:
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
结果如图所示:
--书中给的只是多了一个order by 进行定义了排序方式(以numorders这一列的升序进行排序)
标签: Sql 学习 第一天 SQL 练习题 建表 sql 语句
声明:本文内容来源自网络,文字、图片等素材版权属于原作者,平台转载素材出于传递更多信息,文章内容仅供参考与学习,切勿作为商业目的使用。如果侵害了您的合法权益,请您及时与我们联系,我们会在第一时间进行处理!我们尊重版权,也致力于保护版权,站搜网感谢您的分享!