查询语句实例

数据库:Northwind

题1:

--要求写一个sql,查询出单笔订单金额超过5000的订单号,客户ID,客户公司名称,订单金额,订单日期。
--思路:先写出计算单笔订单金额的sql,再联合客户表、订单表查询相关字段

--单笔订单金额
select OrderID,SUM(UnitPrice*Quantity*(1-Discount)) from [Order Details]
group by OrderID
having SUM(UnitPrice*Quantity*(1-Discount))>5000 

 

--方法一
with OrderInfo 
as(
select OrderID,SUM(UnitPrice*Quantity*(1-Discount)) as totalPrice from [Order Details] od
group by od.OrderID
having SUM(UnitPrice*Quantity*(1-Discount))>5000)

select o.OrderID as '订单编号',o.CustomerID as '客户ID',o.OrderDate as '订购日期',c.CompanyName as '公司名称',oi.totalPrice as '总金额' from OrderInfo oi,Orders o,Customers c 
where o.CustomerID = c.CustomerID and oi.OrderID = o.OrderID


--方法二
select [order details].orderId,orders.customerId,customers.companyName,sum(unitprice*Quantity*(1-discount))as 总价,orderdate
  from orders,customers,[order details]
   where orders.orderId=[order details].orderId and orders.customerId=customers.customerId--连接表条件
      group by [order details].orderId,orders.customerId,customers.companyName,orderdate
         having sum(unitprice*Quantity*(1-discount))>5000--单笔订单总额大于5000
--方法三
with query
as(
    select OrderID,SUM(UnitPrice*Quantity*(1-Discount)) as totalPrice from [Order Details] od
group by od.OrderID)

select
    o.OrderID,
    c.CustomerID,
    c.CompanyName,
    q.totalPrice,
    o.OrderDate
  from Customers c 
    inner join Orders o 
        on c.CustomerID = o.CustomerID
    inner join query q
        on o.OrderID = q.OrderID 
where q.totalPrice > 5000 

 

--题2,统计每个分类中,每个产品,每年的销售额;要求按分类升序排列,年度升序排列,销售额降序排列
--思路:首先是计算每个订单明细的订单价格;其次再将这个明细价格与分类表、产品表、订单表关联;
--然后按分类、年度分组查询,对价格进行求和;最后按要求排序即可

with query    --每个订单明细的订单价格
as(
    select od.OrderID,od.ProductID,(od.UnitPrice*od.Quantity*(1-od.Discount)) as totalPrice from Products p
    inner join [Order Details] od
    on od.ProductID = p.ProductID
),
query2
as(select Categories.CategoryID, --种类编号
        Categories.CategoryName, --种类名称
        Products.ProductName, --产品名称
        Orders.OrderDate, --订购日期
        query.totalPrice --每个订单明细的价格
    from Categories
    inner join(Products 
                inner join(Orders 
                            inner join query
                            on Orders.OrderID = query.OrderID)
                on Products.ProductID = query.ProductID)
        on Categories.CategoryID = Products.CategoryID)

select CategoryId,
      CategoryName,
      ProductName,
      DATEPART(YEAR,OrderDate) as YEAR,
      SUM(totalPrice) AS PRODUCTSALES
    from query2
  group by 
       categoryId,
       categoryName,
       ProductName,
       Datepart(year,orderdate)
  order by
       categoryId,
       datepart(year,orderdate),
       productSales desc

 

 

 

Northwind数据库关系:

posted @ 2013-08-26 19:12  CN.QS  阅读(362)  评论(0编辑  收藏  举报