0

I'm trying to get SQL to generate a count of rows based on 2 values, from a table like shown below

Table Data:

ID NAME VALUE device_id
1 name_1 enabled 1
2 name_2 enabled 2
3 name_3 enabled 3
4 name_1 disabled 1
5 name_2 disabled 4
6 name_3 disabled 6
1 name_1_ts 1
2 name_2_ts 2
3 name_3_ts 5
.
.
.
99999 name_1 enabled 8329
100000 name_2 disabled 5

Return data that I want to generate

count(*) name value
500 name_1 enabled
1000 name_2 enabled
3500 name_3 enabled
1500 name_1 disabled
2000 name_2 disabled
1500 name_3 disabled

I'm trying

select count(*), name, value 
from TABLE 
where value = 'enabled' or value = 'disabled' 
group by name, value;

But it's not generating the results I'm looking for. What am I doing wrong here, and what I can I do fix it?

3
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. Commented Nov 12 at 18:10
  • 1
    I removed conflicting tags, please specify if you are using mysql or mariadb Commented Nov 12 at 18:31
  • But it's not generating the results I'm looking for. Please include the results that you are looking for. We're not psychic. Commented Nov 12 at 21:28

2 Answers 2

1

It looks like you want the enableds first, then the disableds. To get that you order by the values, then the names. The values you need in descending order, because enabled comes before disabled in lexical order.

Start with this:

select count(*),name, value
  from TABLE
 group by value, name
 order by value desc, name;

Then, maybe you can filter by the values if you need to.

select count(*),name, value
  from TABLE
 where value = 'enabled' or value = 'disabled'
 group by value, name
 order by value desc, name;
Sign up to request clarification or add additional context in comments.

2 Comments

Out of curiosity, why using where value = 'enabled' or value = 'disabled' and not where value in ('enabled','disabled') ?
IN(list, of, items) sometimes is handled suboptimally by the query planner. I've been bitten by it often enough that I avoid it. Of course, OR is also sometime handled suboptimally.
0

O. Jones

Thanks for the help, this fixed my issue. The query I ended up using was

select count(*), name, value
from TABLE
where name not like '%ts%'
group by value, name
order by name;

And this did exactly what I needed.

1 Comment

How does name not like '%ts%' come into it? Nothing in your questions mentions this.

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.