SQL按日期降序表达式

时间:2016-01-27 10:34:37

标签: mysql sql

我有2个表,Worker和Worker_Balance:

---------------           ------------------
|  Worker     |           | Worker_Balance |
|-------------|<----------|----------------|
|             |           | INT workerBID  |
| ...         |           | INT amount     |
---------------           | INT workerID   |
                          | DATE timestamp |
                          ------------------

以及以下sql-query:

SELECT Worker.ID, Worker.xy, SUM(Worker_Balance.amount)
FROM Worker
JOIN Worker_Balance ON WorkerBalance.workerID = Worker.workerID
GROUP BY Worker.ID, Worker.xy

我需要按最新时间戳排序的结果,但最旧的必须是第一个。因此,最后一笔交易最早的工人是第一位。

1 个答案:

答案 0 :(得分:2)

您需要GROUP BY才能汇总和ORDER BY才能进行排序:

SELECT Worker.ID
    ,Worker.xy
    ,MAX(Worker.TIMESTAMP) last_transaction
    ,SUM(Worker_Balance.amount)
FROM Worker
JOIN Worker_Balance ON WorkerBalance.workerID = Worker.workerID
GROUP BY Worker.ID
    ,Worker.xy
ORDER BY last_transaction