Question

I have a database that store transaction logs, I would like to count all the logs for that day and group them based on prod_id

MySQL table structure:

Table name = products

+------+---------+------------+--------+
| ID   | PROD_ID | DATE       | PERSON |
+------+---------+------------+--------+
|    1 |       2 | 1400137633 |      1 |
|    2 |       2 | 1400137666 |      1 |
|    3 |       3 | 1400137125 |      2 |
|    4 |       4 | 1400137563 |      1 |
|    5 |       2 | 1400137425 |      2 |
|    6 |       3 | 1400137336 |      1 |
+------+---------+------------+--------+

MYSQL CODE:

 $q = 'SELECT count(ID) as count 
         FROM PRODUCTS 
        WHERE PERSON ='.$db->qstr($person).' 
          AND DATE(FROM_UNIXTIME(DATE)) = DATE(NOW())';

so what I get is the number of items for the given date. Since the date is the same as all other entries. however I would like to group the items by prod_id, I tried GROUP BY PROD_ID but that did not give me what I want. I would like it to group if the PROD_ID is multiple and the date is the same display as one entry while still count the others

so here I should get an output ($Person = 1).... 2+2+2=1 +3 +4 so total should be 3

any suggestions?

Was it helpful?

Solution

Use DISTINCT with COUNT on PROD_ID.

Example:

SELECT count( distinct PROD_ID ) as count 
 FROM PRODUCTS 
 WHERE PERSON = 1  -- <---- change this with relevant variable
   AND DATE( FROM_UNIXTIME (DATE ) ) = curdate();

And I suggest you to use Prepared Statement to bind values.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top