Home > Back-end >  Count all rows and add a certain int from column of each result row into overall count
Count all rows and add a certain int from column of each result row into overall count

Time:08-27

I have a table consisting of columns tblEventID, isSafeSlot, plusOnes. I want to retrieve the number of rows where tblEventID is equal to X and isSafeSlot is equal to true, and if both are true, also check the column plusOnes for that one row. This column will hold an int from 0 to 99. I need to add those numbers also into the count.

So say we have this table:

tblEventID / isSafeSlot / plusOnes
100 / true / 0
100 / true / 53
100 / false / 0 
101 / true / 99 

And I am giving it tblEventID 100, the count result should be 55 (two rows making the count 2, plus one row has the number 53 stored under plusOnes, result 55)

How can I make this inside one query?

CodePudding user response:

Filter the rows of the table with your conditions and aggregate:

SELECT COUNT(*)   SUM(plusOnes)
FROM tablename
WHERE tblEventID = 100 AND isSafeSlot;

or, simpler:

SELECT SUM(plusOnes   1)
FROM tablename
WHERE tblEventID = 100 AND isSafeSlot;

CodePudding user response:

SELECT COUNT(*)   SUM(plusOnes) AS total
FROM `say_we_have_this_table`
WHERE tblEventId = 100
 AND isSafeSlot = true;
  • Related