tags:

views:

31

answers:

3

The idea is to get in the result a new column describing the user "category". This category could for example be "under18","normal","over65" based on user age.

That is, for each user in my table I want to get as result its ID and this description in a column called "category".

How would you proceed? I need this because the data will later go to a JSON object and to a ExtJS grid for visualization.

+4  A: 

As your category is data derived from existing data, the use of a new column in the database for it should be discouraged. Instead, you could just add a case statement to your database query to work out the category as required or put it into a view in the database.

The query would look something like this:

select
    ...
    case when Age < 18 then 'under18'
         when Age > 65 then 'over65'
         else 'normal' end AS Age_Category
from ...
ar
A: 

At query level this can be done with CASE expression:

select
  user_id,
  case when age < 18 then 'under18'
       when age <=65 then 'normal'
       when age > 65 then 'over65'
       else null end as category
from
  Users

However i would recommend to move this from query level to application level. You already have application logic to construct JSON from the dataset, this would be a more appropriate place to generate category name from age value.

Constantin
A: 

If your DBMS supports it, I would create a UDF (user defined function) that passes in the age from your table and returns category. This has the advantage of being reusable and a little cleaner. If this is for one query only just use the CASE statement.

Jay
One problem with using a UDF is that it incurs an overhead each time it needs to be called. For complex categories, however, they can be the only way.
ar
Does that case statement syntax actually work? and if so in which dbms's?
ar
My bad, you can only do it the way I did when you are comparing a value exactly, not when using less than or greater than. That is how I usually write them when doing straight equality tests since it keeps them a little shorter.
Jay
As for UDFs, I agree there is some overhead but if this was part of a big complex system, it would be a lot easier to maintain when adding a new category "40 somethings" :-)
Jay