简体   繁体   中英

MySQL query does not return DISTINCT nor TIMESTAMPDIFF

Preface: I'm an utter newbie at MySQL.

My goal is to produce a table that shows three columns: user_id , number of days an Event occurred (call this eventDays ), and the number of days since the very first Event (call this totalDays ).

By generating this table, I'll be able to produce a ratio that shows how many eventDays:totalDays (this will be done in Excel).

Below is my query. It produces no errors , but the output is wrong: while the user_id is retuned as expected, eventDays always returns a value of '1' and totalDays returns a value of '0' for every given user_id .

Thank you in advance, and again: n00b alert...

SELECT t1.user_id, COUNT(DISTINCT YEAR(t1.time_stamp), MONTH(t1.time_stamp), DAY(t1.time_stamp)) AS 'Number of unique days where an Event occured', TIMESTAMPDIFF(DAY, t1.time_stamp, t2.time_stamp) AS 'Total days since First Event'
FROM (
    SELECT *
    FROM first.table
    GROUP BY user_id
    ORDER BY time_stamp ASC) AS t1
       INNER JOIN (
            SELECT *
            FROM second_table
            GROUP BY user_id
            ORDER BY time_stamp DESC) AS t2
          ON t1.user_id = t2.user_id
          GROUP BY t1.user_id
          ORDER BY COUNT(DISTINCT YEAR(t1.time_stamp),MONTH(t1.time_stamp), DAY(t1.time_stamp)) DESC;

it's really hard to help you on this when there is no example of the data you are querying against. if you can get back with that i may be of more help. regardless, see below:

". . . number of days an Event occurred (call this eventDays) . . . "

-- i believe you are misusing the day() function . day() will return you and integer between 1 and 31 for the day of the month. It seems like count() of occurrences or sum() of a generated flag field in the query would give you want you want.

". . . and the number of days since the very first Event (call this totalDays). . . "

-- kind of hard to say with this one since you are using the function correctly. first thought is maybe one date is less than the other and it does not compute negatives or absolute values? i don't recall, mysql is not my regular rdbms.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM