我有以下查询:
SELECT transactions.created,
installments.*,
transactions.installment_id,
Sum(transactions.amount) AS s,
Sum(installments.amount) AS s1
FROM installments
LEFT OUTER JOIN transactions
ON transactions.installment_id = installments.id
WHERE installments.customer_id = ?
GROUP BY installments.id
给了我错误
org.h2.jdbc.JdbcSQLException:列“TRANSACTIONS.CREATED”必须在 GROUP BY列表; SQL语句:
但我需要创建的字段,不想在GROUP_BY中使用它。
答案 0 :(得分:0)
SELECT *,s,S1,created
FROM installments
LEFT OUTER JOIN
(
SELECT SUM(transactions.amount) AS s, SUM(installments.amount) AS
s1,created
FROM transactions
GROUP BY created
) A ON A.installment_id = installments.id
WHERE installments.customer_id=?
答案 1 :(得分:0)
将其包含在GROUP BY
中修复了语法问题:
SELECT t.created, i.*,
Sum(t.amount) AS s,
Sum(i.amount) AS s1
FROM installments i LEFT OUTER JOIN
transactions t
ON t.installment_id = i.id
WHERE i.customer_id = ?
GROUP BY i.id, t.created;
但真正的问题是你可能有多个交易。您想要哪个created
值?你可能想要更像的东西:
SELECT Min(t.created) as created, i.*,
Sum(t.amount) AS s,
Sum(i.amount) AS s1
FROM installments i LEFT OUTER JOIN
transactions t
ON t.installment_id = i.id
WHERE i.customer_id = ?
GROUP BY i.id;
我应该注意到s1的计算可能是错误的,因为它会乘以事务数量。我认为更像这样的事情可能就是你的意图:
SELECT t.created, i.*,
t.amount as s,
Sum(i.amount) as s1
FROM installments i LEFT OUTER JOIN
(SELECT t.installment_id, t.created as created,
SUM(t.amount) as s
FROM transactions t
GROUP BY t.installment_id
) t
ON t.installment_id = i.id
WHERE i.customer_id = ?
GROUP BY i.id, t.created, t.amount;