请查看以下代码
SELECT ongoing_portfolio.*,
Portfolio.Activation
FROM Ongoing_Portfolio
INNER JOIN Portfolio ON Ongoing_Portfolio.idPortfolio = Portfolio.idPortfolio
WHERE ongoing_portfolio.`idPortfolio`= 2 ORDER BY `Updated_Date` DESC LIMIT 4
SELECT SUM(`Transaction_Amount`) AS `Total`
FROM `transactions`
WHERE `idPortfolio`= 2 AND `Transaction_TimeStamp` <= "2016-12-17"
其实我在这里要做的就是这个。
Updated_Date
日期的总交易。 (第二个问题)现在,我真的需要在一个查询中执行此操作,所以我在下面尝试过。
SELECT ongoing_portfolio.*,
Portfolio.Activation,
SUM(Transactions.`Transaction_Amount`) AS `Total` WHERE `Transaction_TimeStamp` <= ongoing_portfolio.`Updated_Date`
FROM Ongoing_Portfolio
INNER JOIN Portfolio ON Ongoing_Portfolio.idPortfolio = Portfolio.idPortfolio
INNER JOIN Transactions ON Transactions.`idPortfolio` = Ongoing_Portfolio.idPortfolio
WHERE ongoing_portfolio.`idPortfolio`= 2 ORDER BY `Updated_Date` DESC LIMIT 4
然而,这会产生错误,因为它说
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE `Transaction_TimeStamp` <= ongoing_portfolio.`Updated_Date`
FROM Ongoing_' at line 3
如何成功完成此一项查询?
答案 0 :(得分:1)
您无法在检索列中使用where条件。 您可以使用if else或when condition for total。
SELECT ongoing_portfolio.*,
Portfolio.Activation,
SUM(case when Transaction_TimeStamp` <= ongoing_portfolio.`Updated_Date`
then Transactions.`Transaction_Amount` end) AS `Total` FROM Ongoing_Portfolio
INNER JOIN Portfolio ON Ongoing_Portfolio.idPortfolio = Portfolio.idPortfolio
INNER JOIN Transactions ON Transactions.`idPortfolio` = Ongoing_Portfolio.idPortfolio
WHERE ongoing_portfolio.`idPortfolio`= 2 group by 'Updated_Date'
ORDER BY `Updated_Date` DESC LIMIT 4