Jump to content

PHP help, how do I count with a condition and 3 records per ID? A Challenge!


RJP1

Recommended Posts

Hi guys,

 

I'm stuck... I need to count users who meet certain conditions on this table:

 

Code:

 

user_id | field_id | value
---------------------------
1       |     1    |   UK
1       |     2    |   Yes
1       |     3    |   1
2       |     1    |   USA
2       |     2    |   No
2       |     3    |   2

 

As you can see, users are grouped in 3's (one row per field). How do I count users who meet these conditions?

 

a) if country (field 1) = specified country AND field 2 = Yes ---> counted as 1

b) if country (field 1) = specified country AND field 2 = Yes AND field 3 = specified number ---> counted as 1

 

Output should be total of a) and b)

 

If anyone could help me with this, that would be awesome! I need the MySQL and PHP statements...

 

Thanks! RJP1

Link to comment
Share on other sites

I don't have time to spoonfeed out all the code, but the simple answer from the SQL side, is that you can count(DISTINCT user_id).  The rest of that is simply constructing the criteria with the appropriate AND and OR's needed.

Link to comment
Share on other sites

This may work. Since I don't have your database and am too lazy to create one, I can't test it. If I am correct the generated query should return a result set with each user ID and their appropriate total. (be sure to replace "table" with the appropriate table name)

 

$country = "USA";
$number  = "1";

$query = "SELECT user_id,
                 SUM (
                   IF (country='{$country}' AND bool='Yes', 1, 0),
                   IF (country='{$country}' AND bool='Yes' AND number='{$number}', 1, 0)
                 ) as total
          FROM (SELECT user_id, value as country
                FROM table
                WHERE field_id = 1) as t1
          JOIN (SELECT value as bool
                FROM table
                WHERE field_id = 2) as t2
            ON t1.user_id = t2.user_id
          JOIN (SELECT value as number
                FROM table
                WHERE field_id = 3) as t3
            ON t1.user_id = t3.user_id";

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.