0

这是我的表结构:

团队

  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

我在这里做错了什么?

4

2 回答 2

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 子句

这篇文章似乎不错,只是为了快速解析,顺序似乎不对,因为它是出于作者的优化偏好而列出的。在这方面,它是一个不错的文章。但是对于复制和粘贴列表以可视化子句的顺序不是:))

于 2013-09-20T13:18:50.877 回答
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;
于 2013-09-20T13:18:43.200 回答