views:

49

answers:

4

I need help to transform data on a table, reducing a series of columns to one single column. An example follows below:

Frequency_1 integer,
Frequency_2 integer,
Frequency_3 integer,
Frequency_4 integer,

These columns currently hold 1 or 0. Only one column will hold 1.

The new column should be defined as

Frequency integer

And this new column should hold a value between 1 and 4, depending on which of the old columns had its value = 1.

Could you suggest an SQL command to accomplish this?

+3  A: 

You could come up with something more complicated if you want, but why not just do this?

SELECT Frequency_1 +
       (Frequency_2 * 2) +
       (Frequency_3 * 3) +
       (Frequency_4 * 4) AS Frequency

To actually make the change, you can create the column first, update the value in the new column, then delete the old columns.

Mark Byers
Elegant. Very nice.
Matthew Wood
Elegant indeed. It works well for this. Not to diminish the CASE based question either. So my +1 to them too.
Krugar
+3  A: 
SELECT
    CASE WHEN Frequency_1 = 1 THEN 1 
         WHEN Frequency_2 = 1 THEN 2 
         WHEN Frequency_3 = 1 THEN 3 
         WHEN Frequency_4 = 1 THEN 4 
         ELSE 0 END AS Frequency
FROM TABLE
Paul Creasey
+1  A: 
update table_name
  set frequency = 
    case when frequency_1 = 1 then 1 else
      case when frequency_2 = 1 then 2 else
        case when frequency_3 = 1 then 3 else
          case when frequency_4 = 1 then 4 
          end
        end
      end
    end
Ray
+1  A: 

Like this:

select Frequency =
  Frequency_1 * 1 +
  Frequency_2 * 2 +
  Frequency_3 * 3 +
  Frequency_4 * 4
from ATable

or this:

select Frequency = case
  when Frequency_1 = 1 then 1
  when Frequency_2 = 1 then 2
  when Frequency_3 = 1 then 3
  when Frequency_4 = 1 then 4
  else 0
end
from ATable
Guffa