0

I have a table with 5 fields. Each field can store a number from 1 - 59.

Similar to countif in Excel, how do I count the number of times a number from 1 - 59 shows up in all 5 fields?

Here's an example for the count of occurances for the number 1 in all five fields:

SELECT SUM(pick_1 = 1 OR pick_2 = 1 OR pick_3 = 1 OR pick_4 = 1 OR pick_5 = 1) AS total_count_1
FROM tbldraw

Hopefully I made sense.

2
  • What do you want you output to look like? 59 rows (1 per digit) with how often in your table that value shows up in all five fields of a record)? Commented Oct 5, 2013 at 14:15
  • Wasn't there an answer here? Commented Oct 5, 2013 at 14:36

3 Answers 3

1

There was an answer here that had a solution. I think this is just a variation.

Step1: Create a numbers table (1 field, called id, 59 records (values 1 -59))

Step2:

SELECT numbers_table.number as number
  , COUNT(tbldraw.pk_record)
FROM numbers_table
LEFT JOIN tbldraw
 ON numbers_table.number = tbldraw.pick_1
   OR numbers_table.number = tbldraw.pick_2
   OR numbers_table.number = tbldraw.pick_3
   OR numbers_table.number = tbldraw.pick_4
   OR numbers_table.number = tbldraw.pick_5
GROUP BY number
ORDER BY number
Sign up to request clarification or add additional context in comments.

Comments

0

How about a two step process? Assuming a table called summary_table ( int id, int ttl), for each number you care about...

insert into summary_table values (1,
    (select count(*)
     from table
     where field1 = 1 or field2 = 1 or field3 = 1 or field4 = 1 or field5 = 1))

do that 59 times, once for each value. You can use a loop in most cases. Then you can select from the summary_table

select *
from summary_table
order by id

That will do it. I leave the coversion of this SQL into a stored procedure for those that know what database is in use.

Comments

0

The ALL() function, which returns true if the preceding operator is true for all parameters, makes the query particularly elegant and succinct.

To find the count a particular number (eg 3):

select count(*)
from tbldraw
where 3 = all (pick_1, pick_2, pick_3, pick_4, pick_5)

To find the count of all such numbers:

select pick_1, count(*)
from tbldraw
where pick_1 = all (pick_2, pick_3, pick_4, pick_5)
group by pick_1

Comments

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.