1

I have two columns of one row of a report that I would like to be based off the same one column in a SQL table.

For example, in the report it should be something like:

ID | Reason       | SubReason
1  | Did not like | Appearance

In the SQL table it is something like:

ID | ReturnReason
1  | Did not like
1  | XX*SR*Appearance
1  | XX - TestData
1  | XX - TestData2

The SubReason column is being newly added and the current SQL query is something like:

SELECT ID, ReturnReason AS 'Reason'
FROM table
WHERE LEFT(ReturnReason,2) NOT IN ('XX')

And now I'd like to add a column in the SELECT statement for SubReason, which should be the value if *SR* is in the value. This however won't work because it also has 'XX' in the value, which is omitted by the current WHERE clause.

1
  • 5
    I hate databases designed like this! Commented Oct 16, 2013 at 13:36

1 Answer 1

2
SELECT t.ID, t.ReturnReason AS 'Reason',
SUBSTRING(t1.ReturnReason,7,10000) as 'SubReason '
FROM t
LEFT JOIN t as t1 on t.id=t1.id and t1.ReturnReason LIKE 'XX*SR*%'
WHERE t.ReturnReason NOT LIKE 'XX%'

SQLFiddle demo

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

3 Comments

Hi @valex, this did produce the result I wanted, however, once adding the JOIN, the query took a very long time to run (went from really quick to about 5 minutes). Any thoughts as to why this is happening? Could it be because the table is approximately 18GB and the query is joining it?
If you can't change table design try to add indexes on ID and ReturnReAson fields
I'm not looking to change table design or add an index if possible, is there any alternative ways to query or methods that might work? There is an index on the ID but not ReturnReason field.

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.