简体   繁体   中英

How to Select last Column in a row on mysql?

How to Select last Column in a row on mysql?

For a table like this:

  ID   qty1    qty2    qty3    qty4   qty5   qty6    qty7 
   1    20      10       90     40     0       0      0
   2    90      80       0       0     0       0      0

The result should be:

ID   last_column_value
 1          40

or

ID   last_column_value
 2          80

Usually I use Select Max(ID) from table if I need last value on 1 column.

The only way I can see to solve it is to do a nasty nested IF as below.

SELECT ID, IF(qty7 <> 0,qty7, IF(qty6 <> 0,qty6, IF(qty5 <> 0,qty5, IF(qty4 <> 0,qty4, IF(qty3 <> 0,qty3, IF(qty2 <> 0,qty2, qty1)))))) last_column_value
FROM qtytable

This results in

ID  LAST_COLUMN_VALUE
1   40
2   80

SQL Fiddle

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