Make a select from three columns (with case expression)

  • HI,

    I have a table (named empresa) which has several fields.

    Three of the fields are:

    perc_cs_publico

    perc_cs_privado

    perc_cs_estrangeiro

    I want to make a select that returns PUBLICO if perc_cs_publico is different from zero and perc_cs_privado and perc_cs_estangeiro are equal to zero.

    It should Return MISTO if perc_cs_publico is different from zero and perc_cs_estrangeiro or perc_cs_privado are different from zero

    IT should return PRIVADO if perc_cs_publico is equal to zero and perc_estangeiro or perc_cs_privado is different from zero.

    How can I do this select?

    Thank you

  • it is a relatively straightforward CASE statement

    CASE WHEN perc_cs_publico <> 0 AND perc_cs_privado = 0 AND perc_cs_estrangeiro = 0 THEN PUBLICO

    WHEN perc_cs_publico <> 0 AND (perc_cs_privado <> 0 OR perc_cs_estrangeiro <> 0) THEN MISTO

    WHEN perc_cs_publico = 0 AND (perc_cs_privado <> 0 OR perc_cs_estrangeiro <> 0) THEN PRIVADO END

    Beware, that if there is a record where all three are zero, you'll get a NULL value because you haven't defined a value for that situation.

    --------------------------------------------------------------------------
    When you realize you've dug yourself into a hole....Step 1...stop digging.

  • I suggest adding a computed column to the table to determine the value: then the definition is only one place, and is thus very easy to change everywhere:

    ALTER TABLE dbo.tablename

    ADD perc_cs_return AS

    CASE WHEN perc_cs_publico <> 0 AND perc_cs_privado = 0 AND perc_cs_estangeiro = 0 THEN perc_cs_publico

    WHEN perc_cs_publico <> 0 AND (perc_cs_privado <> 0 OR perc_cs_estangeiro <> 0) THEN perc_cs_misto

    WHEN perc_cs_publico = 0 AND (perc_cs_privado <> 0 OR perc_cs_estangeiro <> 0) THEN perc_cs_privado

    ELSE NULL END

    SQL DBA,SQL Server MVP(07, 08, 09) A socialist is someone who will give you the shirt off *someone else's* back.

  • Thank you for your reply but in this case I prefer the first solution.

    Thank you all for the help.

Viewing 4 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic. Login to reply