how to select max of mixed string/int column?

て烟熏妆下的殇ゞ 提交于 2019-11-28 09:55:09
nakosspy

HKL9 (string) is greater than HKL15, because they are compared as strings. One way to deal with your problem is to define a column function that returns only the numeric part of the invoice number.

If all your invoice numbers start with HKL, then you can use:

SELECT MAX(CAST(SUBSTRING(invoice_number, 4, length(invoice_number)-3) AS UNSIGNED)) FROM table

It takes the invoice_number excluding the 3 first characters, converts to int, and selects max from it.

select ifnull(max(CONVERT(invoice_number ,SIGNED INTEGER)),0) from invoice_header where invoice_number REGEXP '^[0-9]+$'

Your problem is more one of definition & design.

Select the invoice number with highest ID or DATE, or -- if those really don't correlate with "highest invoice number" -- define an additional column, which does correlate with invoice-number and is simple enough for the poor database to understand.

select INVOICE_NUMBER 
from INVOICE_HEADER
order by ID desc limit 1;

It's not that the database isn't smart enough.. it's that you're asking it the wrong question.

This should work also

SELECT invoice_number
FROM invoice_header
ORDER BY LENGTH( invoice_number) DESC,invoice_number DESC 
LIMIT 0,1

After a while of searching I found the easiest solution to this.

select MAX(CAST(REPLACE(REPLACE(invoice_number , 'HKL', ''), '', '') as int)) from invoice_header
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!