[英]Mysql select sum(price) last month
I have this tables 我有这张桌子
stk
+---------+--------------+
| Field | Type |
+---------+--------------+
| id | int(11) |
| name | varchar(255) |
| type_id | int(11) |
+---------+--------------+
stk_type
+-------+--------------+
| Field | Type |
+-------+--------------+
| id | int(11) |
| name | varchar(255) |
| price | int(11) |
+-------+--------------+
customer
+-------+--------------+
| Field | Type |
+-------+--------------+
| id | int(11) |
| fio | varchar(255) |
+-------+--------------+
and sales
+-------------+-----------+
| Field | Type |
+-------------+-----------+
| id | int(11) |
| customer_id | int(11) |
| stk_id | int(11) |
| date | timestamp |
+-------------+-----------+
I need to select how much money i got for last month; 我需要选择上个月赚多少钱; i don't know how to select it in one query.
我不知道如何在一个查询中选择它。
SELECT stk_id FROM sales
WHERE date >= DATE_SUB( CURDATE(), INTERVAL 1 MONTH )
So now i have all the stk ids from last month, and i need to count sum, but how can i do it if i have duplicated keys: for example: 所以现在我拥有上个月的所有stk ID,我需要计算总和,但如果我有重复的密钥,我怎么能这样做:例如:
If last query returns stk_id
's 1,1,1,2 ,3,3 how can i count the sum if price in stk_type
equals next: 如果最后一个查询返回
stk_id
,如果stk_type
价格等于下一个,我如何计算总和:
id 1 price 100
id 2 price 200
id 3 price 150
so for this example i should get this result 800; 所以对于这个例子我应该得到这个结果800;
I need to select all the stk_id and somehow to select price and count the sum. 我需要选择所有stk_id并以某种方式选择价格并计算总和。 Looking for help, thanks.
寻求帮助,谢谢。
SELECT sales.stk_id, sum(stk_type.price)
FROM sales LEFT JOIN stk_type ON (sales.stk_id=stk_type.id)
WHERE date >= DATE_SUB( CURDATE(), INTERVAL 1 MONTH )
GROUP BY sales.stk_id;
I'm assuming "sales.stk_id=stk_type.id" is how they relate? 我假设“sales.stk_id = stk_type.id”是如何相关的?
EDIT: forgot the where clause. 编辑:忘了where子句。
try this sql query 试试这个SQL查询
SELECT stk_id, SUM(price) FROM sales
LEFT JOIN stk ON stk_id = stk.id
LEFT JOIN stk_type ON type_id = stk_type.id
WHERE date >= DATE_SUB( CURDATE(), INTERVAL 1 MONTH )
GROUP BY stk_id
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.