user2210516
user2210516

Reputation: 683

SQL Query that gives me last column with a value in it

So let's say i have a table with 6 columns col1-col6

Sometimes i will have values in the all 6 columns and sometimes maybe just in 3 or 5. It depends. The other columns will be null.

In my query i want a select from col1 and the last column with value in. It's becuase this column hold a total that need.

If the total would be fix in for example col6 i could make a easy query and say

SELECT col1,col6 from mytable

but the problem is i have to find out in with column the total is. It could be in any of col2-col6.

pls look at my fiddle for better understanding, in the example in fiddle i want to have col1, col5 back.

http://sqlfiddle.com/#!6/e3aeb/2

Upvotes: 3

Views: 568

Answers (1)

jarlh
jarlh

Reputation: 44766

Use COALESCE to pick "last" non-null column.

select col1, coalesce(col6, col5, col4, col3, col2) from mytable

Upvotes: 5

Related Questions