FROM和JOIN上的SQL语法错误

时间:2018-01-18 05:36:52

标签: mysql sql

有人能指出我为什么这个SQL查询出错了吗?

http://sqlfiddle.com/#!9/40058/2

预期结果是

在表格中获取Product的名称,

该产品的销售额,

金额(transactionamount) 和净额(statementdebit)

4 个答案:

答案 0 :(得分:4)

查询中的一些错误

  • SUM(transaction.transactionamount AS Amount
  • 上缺少结束括号
  • 选择例如聚合函数后的额外空格COUNT ()

这是工作SQL

SELECT 
DISTINCT transaction.transactionservicetype AS Product,
COUNT(transaction.transactionid) AS Count2,
SUM(transaction.transactionamount) AS Amount,
SUM(statement.statementdebit) AS NetCost
FROM transaction 
RIGHT JOIN statement ON transaction.transactionid = statement.transactionid
WHERE transaction.transactiondate = '2018-01-17' AND transaction.transactionservicetype = 'LBread';

Working SQL Fiddle

答案 1 :(得分:1)

交易是一个关键字请用反引号 transaction

覆盖

您在 transaction.transactionamount

之后缺少一个括号

另一件事COUNT ()SUM ()应该像COUNT()SUM()在功能中不需要额外的空格。

SELECT 
DISTINCT `transaction`.transactionservicetype AS Product,
count(`transaction`.transactionid) AS Count,
sum(`transaction`.transactionamount) AS Amount,
sum(statement.statementdebit) AS NetCost
FROM `transaction` 
RIGHT JOIN statement ON `transaction`.transactionid = 
statement.transactionid
WHERE `transaction`.transactiondate = '2018-01-17' AND 
`transaction`.transactionservicetype = 'LBread';

答案 2 :(得分:1)

Missing Closing parentheses on "SUM(transaction.transactionamount AS Amount" and 
Extra Spaces between COUNT(),SUM() function like "SUM (transaction.transactionamount):

Updated query as per  below using left outer join and 
SQL-Fiddle is "http://sqlfiddle.com/#!9/40058/92" : 

SELECT 
T.transactionservicetype AS Product,
COUNT(T.transactionid) AS CountTotal,
SUM(T.transactionamount) AS Amount,
SUM(S.statementdebit) AS NetCost 
FROM statement S  
left outer join transaction T  ON T.transactionid = S.transactionid
WHERE T.transactiondate = '2018-01-17' AND T.transactionservicetype = 'LBread'
group by T.transactionservicetype;

答案 3 :(得分:0)

希望它会对你有所帮助,因为你的表命名字段命名,我有点混淆。

这是我的解决方案 http://sqlfiddle.com/#!9/40058/83/0

sql查询:

    SELECT sum(a.statementdebit) debit,count(a.statementdesc) tot_prod,
sum(b.transactionamount) amount,a.statementdesc
FROM 
statement a
JOIN transaction b on a.transactionid=b.transactionid
where b.transactiondate = '2018-01-17'
group by a.statementdesc