Combine SQL queries for same column.

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • markyodo
    New Member
    • May 2014
    • 1

    Combine SQL queries for same column.

    Hello all this is my first post.
    I am trying to strip some unwanted text from a column containing department names.

    This first query strips all characters after the colon in the name:
    Code:
    SELECT
    CASE WHEN CHARINDEX(':', DB.Table.DEPT)>0 
    THEN
    LEFT(DB.Table.DEPT, CHARINDEX(':', DB.Table.DEPT)-1) 
    ELSE 
    DB.Table.DEPT
    END
    FROM
    DB.Table
    The second query strips the prefix from the name:
    Code:
    SELECT
    REPLACE(
    REPLACE(
    REPLACE (DB.Table.DEPT,'[NA1] ','') 
    ,'[NA2] ', '')
    ,'[NA3] ', '')
    FROM
    DB.Table
    Both of these work great independent of each other, but when I try to combine them it fails.
    Code:
    SELECT
    CASE WHEN CHARINDEX(':', DB.Table.DEPT)>0 
    THEN
    LEFT(DB.Table.DEPT, CHARINDEX(':', DB.Table.DEPT)-1) 
    ELSE 
    DB.Table.DEPT
    END
    FROM
    (SELECT
    REPLACE(
    REPLACE(
    REPLACE (DB.Table.DEPT,'[NA1] ','') 
    ,'[NA2] ', '')
    ,'[NA3] ', '')
    FROM
    DB.Table)
    I could really use some guidance with this.
    Thanks in advance.
    Last edited by Rabbit; May 13 '14, 04:01 PM. Reason: Please use [code] and [/code] tags when posting code or formatted data.
  • Rabbit
    Recognized Expert MVP
    • Jan 2007
    • 12517

    #2
    Please use code tags when posting code or formatted data.

    The problem with your combined query is that you never give the expression you created an alias. You also didn't alias your subquery.

    Comment

    • landrew21
      New Member
      • Apr 2014
      • 2

      #3
      With what Rabbit said try something like
      Code:
      SELECT
      	CASE WHEN CHARINDEX(':', A.DEPT)>0 
      	THEN
      	LEFT(A.DEPT, CHARINDEX(':', A.DEPT)-1) 
      	ELSE 
      	A.DEPT
      	END
      FROM
      	(SELECT
      	REPLACE( REPLACE( REPLACE (DB.Table.DEPT,'[NA1] ','') ,'[NA2] ', '')	,'[NA3] ', '') as DEPT
      	FROM
      	DB.Table) A

      Comment

      Working...