这是我的表结构:
小组
t_id => int(11)
t_name => varchar(256)
销售
s_id => int(11)
s_amount => int(11)
s_date => date
team_id => int(11)
我想总结所有团队在特定时间段内的所有销售情况。这是我的SQL命令:
SELECT
t_name,
SUM(s_amount) as total_amount,
FROM teams
JOIN sales ON sales.team_id=teams.t_id
GROUP BY sales.team_id
WHERE s_date BETWEEN '2013-09-01'
AND '2013-09-08';
如果我在phpmyadmin中执行此命令,则说:
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE s_date BETWEEN '2013-09-01' AND '2013-09-08' L' at line 10
我在这里做错了什么?
答案 0 :(得分:3)
订单错误
SELECT
t_name,
SUM(s_amount) as total_amount
FROM teams
JOIN sales ON sales.team_id=teams.t_id
WHERE s_date BETWEEN '2013-09-01'
AND '2013-09-08'
GROUP BY sales.team_id;
GROUP BY前的位置:
1.SELECT条款
2.FROM条款
3.WHERE条款
4.GROUP BY子句
5.HAVING条款
6.ORDER BY子句
(this article似乎是一个很好的,除了快速解析,顺序似乎是错误的,因为它列出了作者的优化偏好。在这方面,它是一个很好的。但是,为了复制和粘贴列表以可视化条款的顺序,它不是:))
答案 1 :(得分:2)
WHERE
子句应该在GROUP BY
之前
SELECT
t_name,
SUM(s_amount) as total_amount
FROM teams
JOIN sales ON sales.team_id=teams.t_id
WHERE s_date BETWEEN '2013-09-01' AND '2013-09-08'
GROUP BY sales.team_id;