Results 1 to 6 of 6
  1. #1
    Join Date
    Jan 2006
    Posts
    28

    Unanswered: Get corresponding column names for certain data

    Hi,

    I have a table with say 3 columns and I want to get all non-null values from these 3 columns AS WELL AS their corresponding column names. So if I have this:

    Code:
    Col1  Col2  Col3
    ----  ----  ----
    Alex        Brik
          Jim   Sam
    Tom   Hook  Caren
    I want the result to look like this:

    Code:
    Name  ColName
    ----  -------
    Alex  Col1
    Tom   Col1
    Jim   Col2
    Hook  Col2
    Brik  Col3
    Sam   Col3
    Caren Col3
    Is there a query to do this? Many thanks.

  2. #2
    Join Date
    Apr 2002
    Location
    Toronto, Canada
    Posts
    20,002
    Code:
    SELECT Col1 AS Name
         , 'Col1' AS ColName
      FROM daTable
     WHERE Col1 IS NOT NULL
    UNION ALL
    SELECT Col2 
         , 'Col2' 
      FROM daTable
     WHERE Col2 IS NOT NULL
    UNION ALL
    SELECT Col3 
         , 'Col3' 
      FROM daTable
     WHERE Col3 IS NOT NULL
    rudy.ca | @rudydotca
    Buy my SitePoint book: Simply SQL

  3. #3
    Join Date
    Mar 2003
    Location
    The Bottom of The Barrel
    Posts
    6,102
    Provided Answers: 1
    Hey, I didn't realize you wrote a book Rudy! That's great!


    opel... why do you have three columns that are storing similar data?
    oh yeah... documentation... I have heard of that.

    *** What Do You Want In The MS Access Forum? ***

  4. #4
    Join Date
    Jan 2006
    Posts
    28
    Thanks alot. Is there a way to make the query slightly dynamic so that it can get the column name without having to hardcode it?

    @Teddy: That was just an example. I guess I'm not very good at coming up with sensible examples!

  5. #5
    Join Date
    Apr 2002
    Location
    Toronto, Canada
    Posts
    20,002
    Quote Originally Posted by opelcorsa
    Is there a way to make the query slightly dynamic so that it can get the column name without having to hardcode it?
    no

    you should redesign the table instead
    rudy.ca | @rudydotca
    Buy my SitePoint book: Simply SQL

  6. #6
    Join Date
    Jan 2006
    Posts
    28
    lol ok thanks again!

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •