5
I am working on a report in Mysql where I need to show a percentage of several events that occurred with a group of entities.
The structure of my table is as follows:
| id | eventoA | eventoB | eventoC | eventoD |
|----|---------|---------|---------|---------|
| 1 | 0 | 0 | 0 | 0 |
| 2 | 1 | 0 | 0 | 0 |
| 3 | 1 | 0 | 0 | 0 |
| 4 | 0 | 0 | 1 | 0 |
| 5 | 0 | 1 | 0 | 0 |
| 6 | 1 | 1 | 0 | 0 |
| 7 | 1 | 1 | 0 | 0 |
| 8 | 1 | 0 | 1 | 0 |
| 9 | 0 | 0 | 1 | 0 |
| 10 | 0 | 0 | 0 | 0 |
The columns EventoA
, EventoB
and so on are like BIT
and are updated by the application when a given event is triggered to that entity. Today I can generate that report with the following query:
SELECT COUNT(`id`) AS `Total`,
SUM(`eventoA`) AS `eventoDisparado`,
COUNT(`id`) - SUM(`eventoA`) AS `eventoNaoDisparado`
FROM tabela;
Query result:
Total: 10, event Available: 5, event Available: 5
But this way I can not combine multiple events because the number of events ends up not hitting:
SELECT COUNT(`id`) AS `Total`,
SUM(`eventoA`) + SUM(`eventoB`) AS `eventoDisparado`,
COUNT(`id`) - SUM(`eventoA`) + SUM(`eventoB`) AS `eventoNaoDisparado`
FROM tabela;
Expected result:
Total: 10, event Available: 6, event Available: 4
Result obtained
Total: 10, event Available: 8, event Available: 2
I’d like to sort of combine the columns eventoA
and eventoB
thus:
| id | eventoA | eventoB | eventoA + eventoB |
|----|---------|---------|-------------------|
| 1 | 0 | 0 | 0 |
| 2 | 1 | 0 | 1 |
| 3 | 1 | 0 | 1 |
| 4 | 0 | 0 | 0 |
| 5 | 0 | 1 | 1 |
| 6 | 1 | 1 | 1 |
| 7 | 1 | 1 | 1 |
| 8 | 1 | 0 | 1 |
| 9 | 0 | 0 | 0 |
| 10 | 0 | 0 | 0 |
You may get the expected result using a OR
bitwise.
It is possible to use such operators directly in a query? What other alternatives I have to achieve the expected result?
I don’t know if I understand what you need but at the very least you can do a function that makes it easier.
– Maniero
Based on the table you displayed, what is the expected result? Could you update the question with this information? If possible in tabular structure, as you showed the table above.
– cantoni
@Cantoni became clearer ?
– gmsantos
Yes, it became clearer @gmsantos, thanks. A question, how many event fields are?
– cantoni
@gmsantos, in SQL Server ran bit by bit operation, we need to see now in Mysql. I’m going to check here.
– cantoni
There are 7 types of events
– gmsantos
Okay, I’ll post an answer here and see if she answers you.
– cantoni