文章来源于网络收集而来,版权归原创者所有,如有侵权请及时联系!
分组数据
GROUP BY
:
GROUP BY
子句将记录分组到汇总行中。GROUP BY
为每个组返回一个记录。GROUP BY
通常还涉及聚合COUNT
,MAX
,SUM
,AVG
等。GROUP BY
可以按一列或多列进行分组。GROUP BY
按分组字段进行排序后,ORDER BY
可以以汇总字段来进行排序。
HAVING
:
HAVING
用于对汇总的GROUP BY
结果进行过滤。HAVING
必须要与GROUP BY
连用。WHERE
和HAVING
可以在相同的查询中。
HAVING
vs WHERE
:
WHERE
:过滤指定的行,后面不能加聚合函数(分组函数)。HAVING
:过滤分组,必须要与GROUP BY
连用,不能单独使用。
返回每个订单号各有多少行数
OrderItems
表包含每个订单的每个产品
order_num |
---|
a002 |
a002 |
a002 |
a004 |
a007 |
【问题】编写 SQL 语句,返回每个订单号( order_num
)各有多少行数( order_lines
),并按 order_lines
对结果进行升序排序。
答案:
SELECT order_num, Count(order_num) AS order_lines
FROM OrderItems
GROUP BY order_num
ORDER BY order_lines
知识点:
count(*)
,count(列名)
都可以,区别在于,count(列名)
是统计非 NULL 的行数;order by
最后执行,所以可以使用列别名;- 分组聚合一定不要忘记加上
group by
,不然只会有一行结果。
每个供应商成本最低的产品
有 Products
表,含有字段 prod_price
代表产品价格, vend_id
代表供应商 id
vend_id | prod_price |
---|---|
a0011 | 100 |
a0019 | 0.1 |
b0019 | 1000 |
b0019 | 6980 |
b0019 | 20 |
【问题】编写 SQL 语句,返回名为 cheapest_item
的字段,该字段包含每个供应商成本最低的产品(使用 Products
表中的 prod_price
),然后从最低成本到最高成本对结果进行升序排序。
答案:
SELECT vend_id, Min(prod_price) AS cheapest_item
FROM Products
GROUP BY vend_id
ORDER BY cheapest_item
返回订单数量总和不小于 100 的所有订单的订单号
OrderItems
代表订单商品表,包括:订单号 order_num
和订单数量 quantity
。
order_num | quantity |
---|---|
a1 | 105 |
a2 | 1100 |
a2 | 200 |
a4 | 1121 |
a5 | 10 |
a2 | 19 |
a7 | 5 |
【问题】请编写 SQL 语句,返回订单数量总和不小于 100 的所有订单号,最后结果按照订单号升序排序。
答案:
# 直接聚合
SELECT order_num
FROM OrderItems
GROUP BY order_num
HAVING Sum(quantity) >= 100
ORDER BY order_num
# 子查询
SELECT a.order_num
FROM (SELECT order_num, Sum(quantity) AS sum_num
FROM OrderItems
GROUP BY order_num
HAVING sum_num >= 100) a
ORDER BY a.order_num
知识点:
where
:过滤过滤指定的行,后面不能加聚合函数(分组函数)。having
:过滤分组,与group by
连用,不能单独使用。
计算总和
OrderItems
表代表订单信息,包括字段:订单号 order_num
和 item_price
商品售出价格、 quantity
商品数量。
order_num | item_price | quantity |
---|---|---|
a1 | 10 | 105 |
a2 | 1 | 1100 |
a2 | 1 | 200 |
a4 | 2 | 1121 |
a5 | 5 | 10 |
a2 | 1 | 19 |
a7 | 7 | 5 |
【问题】编写 SQL 语句,根据订单号聚合,返回订单总价不小于 1000 的所有订单号,最后的结果按订单号进行升序排序。
提示:总价 = item_price 乘以 quantity
答案:
SELECT order_num, Sum(item_price * quantity) AS total_price
FROM OrderItems
GROUP BY order_num
HAVING total_price >= 1000
ORDER BY order_num
检查 SQL 语句
OrderItems
表含有 order_num
订单号
order_num |
---|
a002 |
a002 |
a002 |
a004 |
a007 |
【问题】将下面代码修改正确后执行
SELECT order_num, COUNT(*) AS items
FROM OrderItems
GROUP BY items
HAVING COUNT(*) >= 3
ORDER BY items, order_num;
修改后:
SELECT order_num, COUNT(*) AS items
FROM OrderItems
GROUP BY order_num
HAVING items >= 3
ORDER BY items, order_num;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论