0

I'm working a DB design regarding how a user launched something. My idea was to have timestamp (DateTime) column, and a method column (varchar).

This 'method' (varchar) could be anything:

  • BUTTON_OK
  • BUTTON_X
  • APP_Y
  • APP_Z
  • etc

How can I COUNT the uses but group some values. In this case I want to have my result:

  • BUTTONS: 20
  • APP_X: 10
  • APP_Z: 14
2
  • Which DBMS are you using? Oracle? PostgreSQL? DB2? Commented Nov 16, 2012 at 10:27
  • Currently for testing MySql but this could be MsSQL or something else. Hopefully this doesn't effect the query. Commented Nov 16, 2012 at 11:23

2 Answers 2

2

You need some way of defining which 'methods' fall into which 'method group'.

One way would be to have a lookup table:

tbl_methodgroup

method_id    Method      Method_group
1            Button_OK   Buttons
2            Button_X    Buttons
3            App_Y       App_Y
4            App_Z       App_Z

then you could use:


select 
b.method_group, 
count(1) 
from
tbl_methodgroup a
  inner join tbl_method b on a.Method=b.Method
group by b.method_group

This method would have the advantage of being scalable as more methods get added. Rather than hand coding queries, which would need to be modified each time.

Sign up to request clarification or add additional context in comments.

2 Comments

So it is not possible to this without an extra table?
Not reliably. You'd need to write some fairly nasty pattern matching code, and then possibly UNION a number of queries together to cope with the rules. It'd be a nightmare to maintain in the long term as the rules change or new methods are added to the list.
1

If the name of the table is tblTest, then the query will look like following:

 SELECT method, COUNT(*) FROM tblTEst Group BY method

Apologies if I missread question, last chance to make it right if you have consistency in the data and grouping scenarios you can do following:

 SELECT LEFT(method,CHARINDEX('_',method)-1), 
        COUNT(*) 
 FROM tblTest 
 GROUP BY LEFT(method,CHARINDEX('_',method)-1)

Otherwise Stuart Moore's answer is correct one.

1 Comment

Unfortunately that doesn't do what @PowerRoy has asked for. They want to group by a 'group' of methods (look at the required results, they want all 'button*' methods counting together rather than seperately (ie; count of Buttons=Count of Button_OK+Count of Button_X)).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.