abipc
abipc

Reputation: 1035

MySQL - assign dynamic categories to records and group them

I have a bunch of records in mysql.. I have 5 five categories (actually time slots like 1-2 pm, 2-3 pm, 3-4 pm etc) which is not present in any field of a record..

I need to query MySQL like this -

Find all results grouped by category1, category2 and so on and within a group sort records by field1, field2 etc..

Actual Query looks like this -

Group all records whose time slot fall in cat1, cat2 and so on and then sort within this group by field1, field2, field3

Upvotes: 0

Views: 25

Answers (1)

Gordon Linoff
Gordon Linoff

Reputation: 1269873

Your query is vague, but you seem to want a case:

select (case when time < <value 1> then 'group1'
             when time < <value 2> then 'group2'
              . . .
        end) as grp,
       count(*), . . .
from table t
group by grp
order by grp;

If you really want the ordering by the time value and not the group name, then use:

order by min(time);

Upvotes: 1

Related Questions