#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jun 2013
    Posts
    22
    Rep Power
    0

    Select once column depending on value of another column


    I want to write a query where I select the value of one column (sep1) only if another column from the same table (alumno1) is not null. How could I do this?
  2. #2
  3. No Profile Picture
    Problem Solver
    Devshed Specialist (4000 - 4499 posts)

    Join Date
    Jan 2001
    Location
    Stockholm, Sweden
    Posts
    4,495
    Rep Power
    534
    I'm guessing that you are asking for something like:
    Code:
    SELECT
      sep1
    FROM
      yourTable
    WHERE
      alumno1 IS NOT NULL
    /Stefan
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jun 2013
    Posts
    22
    Rep Power
    0
    Ok thanks.

    So how can I expand the query to select various columns with the a specific condition for each column?

    that is to say:

    Select Sep1 from groups where alumno1 is not null, Sep2 from groups where alumno2 is not null etc
  6. #4
  7. No Profile Picture
    Contributing User
    Devshed Regular (2000 - 2499 posts)

    Join Date
    Mar 2006
    Posts
    2,442
    Rep Power
    1688
    Depending on your actual requirement you may want to look at the UNION clause:
    Code:
    SELECT
      "sep1" AS theColumn,
      sep1
      FROM yourTable
        WHERE alumno1 IS NOT NULL
    UNION ALL
    SELECT
      "sep2",
      sep2
      FROM yourTable
        WHERE alumno2 IS NOT NULL
    The moon on the one hand, the dawn on the other:
    The moon is my sister, the dawn is my brother.
    The moon on my left and the dawn on my right.
    My brother, good morning: my sister, good night.
    -- Hilaire Belloc
  8. #5
  9. SQL Consultant
    Devshed Supreme Being (6500+ posts)

    Join Date
    Feb 2003
    Location
    Toronto Canada
    Posts
    27,143
    Rep Power
    4274
    Originally Posted by Carrilo
    So how can I expand the query to select various columns with the a specific condition for each column?
    chances are good this wouldn't be nearly as difficult if you normalize your data

    whenever you have many columns all with the same name and a numeric suffix, that's a sure sign of a bad data model

    do a SHOW CREATE TABLE and we'll help you redesign it
    rudy.ca | @rudydotca
    Buy my SitePoint book: Simply SQL
  10. #6
  11. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jun 2013
    Posts
    22
    Rep Power
    0
    The union all query works thanks

IMN logo majestic logo threadwatch logo seochat tools logo