SQL错题集

Group by & Having

  1. where条件语句后面不能加聚合函数
  2. having 不能单独使用,必须和group by 联合使用
  3. 当聚合列和非聚合列出现在一起时必须使用group by。

链接:MYSQL中何时使用group by

聚集函数
COUNT()
SUM()
AVG()
MAX()
MIN()

例题1. SQL89

# 方法一:最简单的方法
select cust_id, sum(quantity*item_price) as total_ordered 
from Orders join OrderItems using(order_num)
group by cust_id #注意要group否则有歧义
order by total_ordered desc;


# 方法二:先选列,再利用子查询选子列
select cust_id, 
# 从列里自定义子查询语句
(
    select sum(quantity*item_price)
    from OrderItems oi
    where oi.order_num = o.order_num
) as total_ordered
from Orders o
order by total_ordered desc;


# 方法三:从表与子表(子查询生成的表)找
select cust_id, total_ordered 
from Orders a,
(
    select order_num, sum(quantity*item_price) total_ordered   
    from OrderItems
    group by order_num #注意生成子表时需要group
) as t
where t.order_num = a.order_num
order by total_ordered desc;

# 方法四:表与子表联结(join)
select cust_id, total_ordered from Orders a
left join 
(
    select order_num, sum(quantity*item_price) as total_ordered
    from OrderItems
    group by order_num #注意生成子表时需要group
) as b
on a.order_num = b.order_num
order by total_ordered desc;

多联结表

例题1. SQL97

#多表联结
select
  a.cust_name,
  b.order_num,
  sum(quantity * item_price) OrderTotal
from
  Customers a
  inner join Orders b on a.cust_id = b.cust_id
  inner join OrderItems c on c.order_num = b.order_num
group by
  cust_name,
  order_num
order by
  cust_name,
  order_num;

#多条件选择,注意group by和select b.order_num否则有歧义
select cust_name, b.order_num, sum(quantity * item_price) OrderTotal
from Customers a, Orders b, OrderItems c
where a.cust_id = b.cust_id and b.order_num = c.order_num
group by cust_name, order_num
order by cust_name, order_num;

#子查询
select cust_name, order_num, 
(
    select sum(quantity*item_price)
    from OrderItems
    where OrderItems.order_num = Orders.order_num

) as OrderTotal
from Customers, Orders
where Customers.cust_id = Orders.cust_id
order by cust_name, order_num
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值