如何修复此数据库排序问题以获取最新结果



我需要从数据库中检索最新数据。 我存储日期一样长。只要我在 Java 端检索和格式化日期,它就可以工作。

但是,如果我从数据库中格式化日期并检索,那么所有日期/时间都相同,例如 30/01/2020。

所以我没有得到准确的结果。

这是我到目前为止尝试过的查询

Select * 
from (select 
Id,
(CASE when TransactionId<10 THEN 'CR-0'||TransactionId ELSE 'CR-'||TransactionId End) as TransactionId,
Description,
case when Date=-1 THEN '' else strftime('%d/%m/%Y', Date / 1000, 'unixepoch') End as Date,
printf('%.2f', Amount) AS Amount,
'Credit' as Type from income_agent WHERE AgentId=1 union all select Id, 
(CASE when TransactionId<10 THEN 'DE-0'||TransactionId ELSE 'DE-'||TransactionId End) as TransactionId,
Description,
case when Date=-1 THEN '' else strftime('%d/%m/%Y', Date / 1000, 'unixepoch') End as Date,
printf('%.2f', Amount) AS Amount,
'Debit' as Type 
from expense_agent WHERE AgentId=1 
union all select 
Id,
(CASE when TransactionId<10 THEN 'RT-0'||TransactionId ELSE 'RT-'||TransactionId End) as TransactionId,
Description,case when Date=-1 THEN '' else strftime('%d/%m/%Y', Date / 1000, 'unixepoch') End as Date,
printf('%.2f', Amount) AS Amount,
'Return' as Type from return_agent  WHERE AgentId=1
)a 
order by Date Desc 
Limit 0,1

如果我不格式化选择结果的日期,则查询有效。

在子查询中包含原始日期:

select . . .
from (select id, date as orig_date, . . .
. . .
) t
order by orig_date;

然后,不要在外部查询中选择它。

或者,只需将日期保留在子查询中,然后在外部查询中设置格式。

最新更新