我有这个SQL查询的问题,查询是自我解释的,所以看着它会告诉你我有什么问题
SELECT customer.customerid,
paymentdata.paidamount,
paymentdata.balanceamount,
sum(paymentreceipt.paidamount) AS Expr1
FROM customer
INNER JOIN paymentdata
ON customer.customerid = paymentdata.customerid
INNER JOIN paymentreceipt
ON customer.customerid = paymentreceipt.customerid
GROUP BY customer.customerid
答案 0 :(得分:2)
您的小组中缺少一些条款。需要包括除聚合列之外的所有列。
答案 1 :(得分:2)
那么你想如何计算其他列,你只是按customerid
进行分组,但是你想要同时显示paymentdata.paidamount
,paymentdata.balanceamount
和paymentreceipt.paidamount
?
考虑该组为每个组返回多行,因此sql-server(或除MySql之外的任何其他rdbms)不知道您要为未分组列显示哪一行。如果您不想选择单行,则必须聚合该列。所以例如使用SUM
,COUNT
,MAX
或AVG
:
例如:
SELECT customer.customerid,
MAX(paymentdata.paidamount) AS MaxPaid,
AVG(paymentdata.balanceamount) AS AverageBalance,
SUM(paymentreceipt.paidamount) AS ReceiptPaidSum
FROM customer
INNER JOIN paymentdata
ON customer.customerid = paymentdata.customerid
INNER JOIN paymentreceipt
ON customer.customerid = paymentreceipt.customerid
GROUP BY customer.customerid
答案 2 :(得分:1)
您需要对group by子句
中未使用的列使用聚合函数SELECT customer.customerid,
sum(paymentdata.paidamount),
sum(paymentdata.balanceamount),
sum(paymentreceipt.paidamount) AS Expr1
FROM customer
INNER JOIN paymentdata
ON customer.customerid = paymentdata.customerid
INNER JOIN paymentreceipt
ON customer.customerid = paymentreceipt.customerid
GROUP BY customer.customerid
答案 3 :(得分:0)
SELECT customer.customerid,paymentdata.customerid,paymentreceipt.customerid
paymentdata.paidamount,
paymentdata.balanceamount,
paymentreceipt.paidamount AS Expr1
FROM customer,paymentdata,paymentreceipt
INNER JOIN paymentdata
ON customer.customerid = paymentdata.customerid
INNER JOIN paymentreceipt
ON customer.customerid = paymentreceipt.customerid
GROUP BY customer.customerid,paymentdata.customerid,paymentreceipt.customerid
答案 4 :(得分:0)
如果您正在进行聚合,那么您可能需要聚合函数:
SELECT customer.customerid,
sum(paymentdata.paidamount),
sum(paymentdata.balanceamount),
sum(paymentreceipt.paidamount) AS Expr1
FROM customer
INNER JOIN paymentdata
ON customer.customerid = paymentdata.customerid
INNER JOIN paymentreceipt
ON customer.customerid = paymentreceipt.customerid
GROUP BY customer.customerid
这可能仍然无法为您提供正确的数字,因为您正在获得付款和收据的交叉加入。如果您想要更好的答案,那么您应该在问题中提供样本数据和预期结果。