Sign up ×
Database Administrators Stack Exchange is a question and answer site for database professionals who wish to improve their database skills and learn from others in the community. It's 100% free, no registration required.

I want to grab a value from a table into two different columns for different values from the same table. Use this query as an example (notice how the select is on the same table aliased as 2 different tables):

SELECT a.myVal, b.myVal 
FROM MyTable a, MyTable b
  a.otherVal = 100 AND
  b.otherVal = 200 AND =

When I run a relatively simple query like this on my dataset, it works - it just takes a long time. Is there a better/smarter way of writing this query?

share|improve this question

2 Answers 2

You could use grouping and conditional aggregating, like this:

  MAX(CASE OtherVal WHEN 100 THEN MyVal END) AS MyVal1,
  MAX(CASE OtherVal WHEN 200 THEN MyVal END) AS MyVal2
FROM MyTable
WHERE OtherVal IN (100, 200)
share|improve this answer

For readability I would rewrite the query using the more modern join syntax. This will clearly separate your join conditions from your filters.

select a.myVal,
  from MyTable a
  join MyTable b on =
where a.OtherVal = 100
  and b.Otherval = 200

For performance, ensure you have proper indexes. In this limited example, ideally you would have a clustered index on ID and a non-clustered index on OtherVal.

After looking at your query, however, I cannot tell just what it is you are trying to accomplish.

share|improve this answer

protected by Community Nov 4 at 12:49

Thank you for your interest in this question. Because it has attracted low-quality answers, posting an answer now requires 10 reputation on this site.

Would you like to answer one of these unanswered questions instead?

Not the answer you're looking for? Browse other questions tagged or ask your own question.