SQL基础

SUM() 函数

以下内容全部copy自互联网,只为使用时快速回忆。


+-----+---------+-------+------------+
| aid | site_id | count | date       |
+-----+---------+-------+------------+
|   1 |       1 |    45 | 2016-05-10 |
|   2 |       3 |   100 | 2016-05-13 |
|   3 |       1 |   230 | 2016-05-14 |
|   4 |       2 |    10 | 2016-05-14 |
|   5 |       5 |   205 | 2016-05-14 |
|   6 |       4 |    13 | 2016-05-15 |
|   7 |       3 |   220 | 2016-05-15 |
|   8 |       5 |   545 | 2016-05-16 |
|   9 |       3 |   201 | 2016-05-17 |
+-----+---------+-------+------------+

对于上面这张表,执行:SELECT SUM(count) AS nums FROM access_log;
结果类似:


image.png

LEFT JOIN ON(左连接)


image.jpeg

对于上面两张表,执行以下语句:

SELECT Persons.LastName, Persons.FirstName, Orders.OrderNo
FROM Persons
LEFT JOIN Orders
ON Persons.Id_P=Orders.Id_P
ORDER BY Persons.LastName

结果是:


image.jpeg

GROUP BY


image.jpeg

对于这张表,我们希望查找每个客户的总金额(总订单),执行以下语句:

SELECT Customer,SUM(OrderPrice) 
FROM Orders
GROUP BY Customer

结果如下:


image.png

group by还可以对多个field进行(至于结果是什么,电脑上安装一个sql软件试一下就可以了),如下:

SELECT Customer,OrderDate,SUM(OrderPrice) 
FROM Orders
GROUP BY Customer,OrderDate

你可能感兴趣的:(SQL基础)