ast1.查询没有折扣的商店
a.
use pubs
SELECT stor_id AS "store id" ,stor_name AS "Store Name"
FROM stores
WHERE stor_id NOT IN
(SELECT stor_id FROM discounts WHERE stor_id IS NOT NULL)
b.
SELECT stor_id AS "store id" ,stor_name AS "Store Name"
FROM stores
WHERE stor_id in
(SELECT stor_id FROM discounts WHERE stor_id IS NULL )
a 和 b 看似相同,但是a 有结果,而b却没有,因为stord_id如果是null 那怎把null值传递回去还是null
2.查询有订单的顾客的第一笔订单。
USE Northwind
select min(o.OrderID) AS ORDERID,o.CustomerID INTO #TEMP_ORDER
from Orders o
group by o.CustomerID
order by CustomerID
select o.OrderID ,o.CustomerID,o.OrderDate
from Orders o inner join #TEMP_ORDER b on o.OrderID=b.OrderID
order by o.CustomerID
#开头命名的表为临时表,存放在tempdb中,如用户使用完毕后不手动删除此临时表,只要断开northwind的连接(比如使用了其他数据库 pubs)则临时表自动被删除。
3. .查询有订单的顾客的第一笔订单,从未有过订单的显示‘NERVER ORDER’。
select cu.CompanyName,
isnull(cast((select MIN(o.orderdate)
from Orders o
where o.CustomerID=cu.CustomerID)as varchar),'NERVER ORDERED'
) as "order date"
from Customers cu
ISNULL 函数,ISNULL(<expression to test>,<replacement value if null>)
其中还使用到了CAST,因为当‘order date’列第一列结果返回的是date类型,但是后面碰到第一列是没有订单的,即'NERVER ORDER'是varchar类型的,不能转换成date类型,所以需要cast来强制转换。cast 列 as 新类型。
4.寻找不仅订购了 chocolade并且订购了 Vegie-spread的用户。
use Northwind
select distinct c.CompanyName
from Customers as c
join
(
select customerid
from orders o
join [Order Details] od
on o.OrderID=od.OrderID
join Products p
on od.ProductID=p.ProductID
where p.ProductName='chocolade') as spen
on c.CustomerID=spen.CustomerID
join
(select customerid
from Orders o
join [Order Details] od
on o.OrderID=od.OrderID
join Products p
on od.ProductID=p.ProductID
where ProductName='vegie-spread') as spap
on c.CustomerID=spap.CustomerID
这个查询用到了派生表———由一个查询结果集的列和行构成。
5.以MM/DD/YY 显示结果
use Northwind
select convert(varchar(10),HireDate,1) from Employees
CAST(expression AS data_type)
CONVERT(data_type,experession [,style])
convert 和cast相比,多了一些日期格式转换功能,但是convert不能代替cast!因为cast是ANSI兼容的,而convert 不是。
6.没有定过单的用户
use Northwind
select cu.CompanyName
from Customers cu
where not exists (select o.CustomerID
from orders o
where cu.CustomerID=o.CustomerID)
EXISTS 一般用于联合连接,因为需要外传递值进子查询,然后子查询返回 TRUE或者FALSE。
7. 用户订单总额超过25000美元,查出这些用户的前五条订单
select * from (
select *, row_number() over( PARTITION by customerid order by orderdate desc) rowid
from (
select o.CustomerID,o.OrderID,o.OrderDate
from Orders o inner join
(
select o.CustomerID,sum(temp.price) as tprice
from Orders o join
(select od.OrderID, sum(od.ProductID*od.Quantity*(1-od.Discount) )as price
from [Order Details] od
group by od.OrderID) as temp
on temp.OrderID=o.OrderID
group by o.CustomerID
having SUM(temp.price)>25000
)tmp
on o.CustomerID=tmp.CustomerID
) aa
)bb
where rowid<=5
说明:返回结果集分区内行的序列号,每个分区的第一行从 1 开始。
语法:ROW_NUMBER () OVER ( [ <partition_by_clause> ]<order_by_clause> ) 。
备注:ORDERBY 子句可确定在特定分区中为行分配唯一 ROW_NUMBER 的顺序。
参数:<partition_by_clause> :将 FROM 子句生成的结果集划入应用了 ROW_NUMBER 函数的分区。
<order_by_clause>:确定将 ROW_NUMBER 值分配给分区中的行的顺序。
返回类型:bigint 。
转载于:https://blog.51cto.com/kingheihei/1209059