MAX(Column) returns me a wrong value

前端 未结 3 1981
猫巷女王i
猫巷女王i 2021-01-28 19:40

I want to retrieve the maximum invoice number from my invoice table where it returns the following when I select all records where you can clearly see the maximum invoice no as

相关标签:
3条回答
  • 2021-01-28 20:04

    It is a pseudo code, try and see it.

    SELECT MAX(CAST(invoice_number AS SIGNED)) from invoice.

    0 讨论(0)
  • 2021-01-28 20:09

    This situation can occur if your invoice_number is stored as a text column e.g. varchar(10). In that case, based on alphabetical order, 9 will be the maximum value.

    Ideally, you should be storing values on which you want to perform numerical operations as numeric datatypes e.g. int. However, if for some reason you cannot change column datatype, you can try casting the column before applying MAX, like so:

    select max (convert(invoice_number, signed integer)) as maxinv from invoice
    

    NOTE: I specifically mention "values on which you want to perform numerical operations" because there are cases where the input text is entirely numeric, such as phone numbers or perhaps credit card numbers, but there is no scenario in which you would want to add 2 phone numbers, or take the square root of a credit card number. Such values should be stored as text.

    0 讨论(0)
  • 2021-01-28 20:11

    It happens because your column is a VARCHAR, try to cast it to UNSIGNED:

    select MAX(CAST(invoice_number AS UNSIGNED)) as maxinv from invoice
    

    As Joshi noticed, if you have negative values you can use SIGNED

    select MAX(CAST(invoice_number AS SIGNED)) as maxinv from invoice
    
    0 讨论(0)
提交回复
热议问题