标签:rod 用户id 9.png ima 笔记 分享 div customers group
列出每个供应商的产品数量
SELECT vend_id, COUNT(*) AS vend_num FROM products GROUP BY vend_id
显示有两个以上订单的顾客
SELECT cust_id, COUNT(*) AS orders FROM orders GROUP BY cust_id HAVING COUNT(*) >= 2
显示出有两个以上的价值在10以上的物品的供应商
1.筛选出所有价格在10以上的商品 2.根据供应商id分组 3.找出数量大于等于2的分组
SELECT vend_id, COUNT(*) AS num_prods FROM products WHERE prod_price >= 10 GROUP BY vend_id HAVING COUNT(*)>=2
检索出总计价格>=50的订单和订单总计价格,按订单总计价格排序输出
1.根据订单号分组 2.计算每个分组的总价格,即每个订单的总价 3.过滤掉总价低于50的订单 4.根据订单总价排序
SELECT order_num, SUM(quantity*item_price) AS ordertotal FROM orderitems GROUP BY order_num HAVING SUM(quantity*item_price)>=50 ORDER BY ordertotal
执行子查询的时候,总是由内到外执行
查询订购了TNT2的所有顾客的信息
(1)检索出包含TNT2的所有订单编号
SELECT order_num FROM orderitems WHERE prod_id = "TNT2"
(2)根据订单编号找出用户ID
SELECT cust_id FROM orders WHERE order_num IN (20005, 20007)
(3)根据用户ID查询该用户信息
SELECT cust_id, cust_name FROM customers WHERE cust_id IN (10001, 10004)
使用子查询
SELECT cust_id, cust_name FROM customers WHERE cust_id IN (SELECT cust_id FROM orders WHERE order_num IN ( SELECT order_num FROM orderitems WHERE prod_id = "TNT2" ) )
显示每个顾客的订单数
(1)显示一个顾客的订单数
SELECT COUNT(*) AS ordernum FROM orders WHERE cust_id = 10001
(2)对每一个客户进行COUNT(*)计算来得到每一个用户的订单数,应将COUNT(*)作为一个子查询
SELECT cust_name, ( SELECT COUNT(*) FROM orders WHERE orders.cust_id = customers.cust_id ) AS orders FROM customers
这是一个相关子查询(涉及外部查询的子查询,外部查询每查询一条记录就要执行一次子查询)
标签:rod 用户id 9.png ima 笔记 分享 div customers group
原文地址:http://www.cnblogs.com/qianbixin/p/6078671.html