❤祝CSDN的各位哥哥姐姐大佬们中秋节快乐呀!❤
SLogan:利用有限的时间,撸起袖子加油干!
字符串的截取:substring(字符串,起始位置,截取字符数)
字符串的拼接:concat(字符串1,字符串2,字符串3,…)
字母大写:upper(字符串)
解题思路:
由题意可知,算总数的话就用SUM()求和函数,还需要用到重命名AS
代码如下:
SELECT SUM(quantity) AS items_ordered
FROM OrderItems
解题思路:
本题和上一题的区别在于多了一个限定条件:确定已售出产品项(prod_id)为"BR01"的总数。还需要用到重命名 AS
代码如下:
SELECT SUM(quantity) AS items_ordered
FROM OrderItems
WHERE prod_id='BR01'
【SQL85】确定 Products 表中价格不超过 10 美元的最贵产品的价格
解题思路:
返回十元以下最高价格,涉及到以下三个知识点
1、最大值函数 max()
2、条件筛选 注意这里是需要 <=10
3、重命名 AS
这一题我一开始做错了,没有考虑到最大值,MAX函数使用的位置出错了,我刚开始用了SUM函数
代码如下:
SELECT MAX(prod_price) AS max_price
FROM Products
WHERE prod_price<=10
解题思路:
先执行GROUP BY order_num,对所有记录分组,分为三组,这里的GROUP BY 也起到了去重的作用,我一开始只考虑到了DISTINCT去重,所以出错了。
再执行SELECT order_num, COUNT(order_num) AS order_lines
最后执行ORDER BY order_lines ASC 对结果进行排序
错误分析:
翻译:SQL_ERROR_INFO:“在没有分组依据的聚合查询中,选择列表的表达式#1包含未聚合的列’OrderItems.order_num’;这与SQL_mode=only_full_GROUP_BY不兼容”
正确代码如下:
SELECT order_num,
COUNT(order_num) AS order_lines
FROM OrderItems
GROUP BY order_num
ORDER BY order_lines ASC
解题思路:
上一题的错处,让我这一题避免了。这个是取对应的最小值,然后升序排序。
参考上一题,这一题就很简单啦,偶尔出出错也不错,长记性了,下次不会再错了!
代码如下:
SELECT vend_id,MIN(prod_price) AS cheapest_item
FROM Products
GROUP BY vend_id
ORDER BY cheapest_item ASC
解题思路:
where—过滤过滤指定的行
having–过滤分组,与group by连用
很少碰到HAVING,刚刚用的是WHERE,直接报错。今天开始牢记GROUP BY 和HAVING 搭配使用!
代码如下:
SELECT order_num
FROM OrderItems
GROUP BY order_num
HAVING SUM(quantity)>=100
ORDER BY order_num ASC
解题思路:
这一题和上面那一题是一样道理,只不过多了一步乘法,依旧是对于GROUP BY 和HAVING 搭配使用的考查,牢记!!
代码如下:
SELECT order_num,SUM(item_price*quantity) AS total_price
FROM OrderItems
GROUP BY order_num
HAVING SUM(item_price*quantity)>=1000
ORDER BY order_num
【SQL90】纠错3
解题思路:
本题应是按照订单号进行分组,而不是按照各个订单的数量去分组
正确代码如下:
SELECT order_num, COUNT(*) AS items
FROM OrderItems
GROUP BY order_num
HAVING COUNT(*) >= 3
ORDER BY items, order_num;
希望大家一键三连呀!!谢谢!!!
祝大家中秋佳节人团圆!