我正在尝试编写一个sql查询,该查询输出产品的标识号(p_id),以及去年(2016年)的销售数量和生成的美元金额。
以下是我的代码
mysql> select id,
-> sum(quantity) as Quantity_Sold
-> sum(amt_paid) as Purchase
-> from transaction
-> where order_date like '%2016%'
-> group by p_id;
以下是我试图查询表格的表格
select * from transaction;
+------+------+------+------------+---------------+----------+------+----------+
| T_ID | P_ID | ID | ORDER_DATE | DELIVERY_DATE | QUANTITY | SP | AMT_PAID |
+------+------+------+------------+---------------+----------+------+----------+
| T1 | P1 | C2 | 2001-01-16 | 2001-02-01 | 2 | 100 | 200 |
| T10 | P11 | C11 | 2001-06-13 | 2001-06-20 | 3 | 25 | 75 |
| T100 | P11 | C11 | 2004-12-06 | 2004-12-11 | 6 | 25 | 150 |
| T101 | P6 | C3 | 2005-01-07 | 2005-01-12 | 1 | 35 | 35 |
| T102 | P3 | C4 | 2005-01-11 | 2005-01-16 | 4 | 120 | 480 |
| T103 | P12 | C5 | 2005-01-26 | 2005-01-31 | 3 | 90 | 270 |
它会出现以下错误 错误1064(42000):您的SQL语法有错误;检查与您的MySQL服务器版本对应的手册,以获得正确的语法,以'sum(数量)作为数量使用 sum(amt_paid)作为购买 其中order_date类似于第2行的'%2016'
enter code here
答案 0 :(得分:0)
group by
和select
匹配:
select p_id, sum(quantity) as Quantity_Sold, sum(amt_paid) as Purchase
from transaction
where order_date >= '2016-01-01' and order_date < '2017-01-01'
group by p_id;
另外,在约会上使用like
是一个非常糟糕的主意。您应该在日期使用日期函数,并使用like
作为字符串。