PaymentHistory表
==========================
UserId | Amount | Date
==========================
1 | 300 | 2014-06-26
3 | 300 | 2014-06-26
2 | 200 | 2014-06-26
1 | 400 | 2014-06-22
1 | 100 | 2014-06-21
首先显示两列是金额之和作为今天具有相同日期的命名“currentEarning”,第二个是基于今天的前一日期命名为“oldEarning”的金额之和。 (对于特定的userId)请参阅输出:
输出
=====================================
UserId | currentEarning | oldEarning |
=====================================
1 | 300 | 500
答案 0 :(得分:2)
您可以使用一个查询执行此操作:
SELECT
SUM(IF(`Date` = CURRENT_DATE, AMOUNT, 0)) AS currentEarning,
SUM(IF(`Date` < CURRENT_DATE, AMOUNT, 0)) AS oldEarning
FROM PaymentHistory
GROUP BY `UserId`
比子查询或两个单独的查询更有效。
答案 1 :(得分:0)
获取当前金额:
SELECT UserId, SUM(Amount) as currentEarning, Date FROM PaymentHistory WHERE UserId = '1' AND DATE(Date) = CURDATE()
获取旧金额:
SELECT UserId, SUM(Amount) as oldEarning, Date FROM PaymentHistory WHERE UserId = '1' AND DATE(Date) != CURDATE()
这应该有效
答案 2 :(得分:0)
SELECT `UserId`,
(SELECT SUM(`Amount`) FROM `PaymentHistory` WHERE `UserID` = t1.`UserId` AND `Date` = t1.`Date`) AS `currentEarning`,
(SELECT SUM(`Amount`) FROM `PaymentHistory` WHERE `UserID` = t1.`UserId` AND `Date` < t1.`Date`) AS `oldEarning`
FROM PaymentHistory AS t1
WHERE t1.`Date` = CURRENT_DATE
GROUP BY t1.`UserId`
HAVING `oldEarning` IS NOT NULL