简体   繁体   中英

Cannot fetch the latest record from the database

I am trying to get the latest record from the Database (Derby database).

I have a BILL table in the database that has a column BillId . The data type of BillId is varchar(15) and is in the format as:

3122022-1

The digits before the "-" (ie, 3122022) are according to the date (3/12/2002). The value after the "-" is the bill counter (ie, 1).

The problem is, when I try to get the latest record from the database using max(BILLID) , it considers 3122022-9 as the maximum/latest record even if the billId 3122022-10 or higher exists.

In simple words, it ignores the 0 or any value placed at the second place after "-". Why is this issue happening and what is the solution??

Here is the table structure: Bill table

I used the following query:

select max(billId) as lastBill from Bill where empName='Hassan' and Date=Current Date;

empName is important as there are 4-5 employees and each will have their own count of Bill.

If I run this query:

select billid from bill order by empName desc;

I get this result:

Bill ids when I sort them by empName column

But if I run the max(billId) query, This is what I get: select max(billId) as lastBill from Bill where empName='Hassan' and Date=Current Date; max(billid) results

I hope I was able to explain my question well. Will be grateful for your help and support.

I tried max(billId)

i came up with sample dataset and query. //Postgres sql

with data as
(
select 'A' as emp_name,'03122022-1' as dated_on
union
select 'A' as emp_name,'03122022-2' as dated_on
union
select 'A' as emp_name,'03122022-3' as dated_on
union
select 'A' as emp_name,'03122022-4' as dated_on
union
select 'A' as emp_name,'03122022-5' as dated_on
union
select 'A' as emp_name,'03122022-6' as dated_on

)
,
data_clean as (
select emp_name,dated_on,
to_date((regexp_split_to_array (dated_on,'-'))[1],'DDMMYYYY') as bill_dated_on,
(regexp_split_to_array (dated_on,'-'))[2] ::int as bill_id
from data)

select emp_name,max(bill_id) from data_clean
where bill_dated_on='20221203'
group by emp_name;

emp_name|max|
--------+---+
A       |  6|

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM