我试过了:
SELECT ProductId AS GmId, (
SELECT SUM(Amount) FROM tmp WHERE ProductId=GmId AND (AssignDate BETWEEN '$Date1' AND '$Date2')
) AS sum0, (
SELECT SUM(Amount) FROM tmp WHERE ProductId=GmId AND (AssignDate BETWEEN '$Date2' AND '$Date3')
) AS sum1 FROM (
SELECT * FROM somerealtable
) tmp GROUP BY ProductId
但mysql显示错误消息table <database name>.tmp doesn't exist!
如何使这项工作?
编辑:sqlfiddle示例here
EDIT2:更复杂的sqlfiddle sample。
答案 0 :(得分:1)
无需使用子查询。您可以使用 JOIN
执行相同的操作试试这个:
SELECT a.ProductId AS GmId,
SUM(IF(b.AssignDate BETWEEN '$Date1' AND '$Date2', b.Amount, 0)) AS sum0,
SUM(IF(b.AssignDate BETWEEN '$Date2' AND '$Date3', b.Amount, 0)) AS sum1
FROM somerealtable a
LEFT JOIN tmp b ON a.ProductId=b.GmId
GROUP BY ProductId