1

Suppose I have the following data:

data

Names X1 X2 X3
Jimmy  1  3  0
Mark   2  0  0
Jimmy  4  0  5

I am having trouble writing a unique query. What I would like return is the last number for each row that is non-zero. So the result would look like

Names Want
Jimmy    3
Mark     2
Jimmy    5

Is there a way to do this?

1 Answer 1

1

If you have a finite number of columns, you can use a CASE statement:

SELECT name, 
  CASE WHEN x3 <> 0 THEN x3
  WHEN x2 <> 0 THEN x2
  ELSE x1 END AS want
FROM myTable;

Here is an SQL Fiddle example.

Sign up to request clarification or add additional context in comments.

1 Comment

@theamateurdataanalyst Glad to help! If this is the answer you stick with, feel free to upvote and accept it so future readers will know what solved your problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.