I have a table that keeps multiple different metrics in the same table. There is one "value" column for the value of the metric, and another column that identifies what the metric actually is. Then, I have an epoch timestamp column, a website column and a primary key ID column.
I am trying to create a MySQL view to show each metric as a separate column, and have each row represent the latest value for each metric per day (there could be multiple rows for one metric in one day, I want to then show only the value for the latest time for that day).
Edit: The value column is just the total at that given time, so none of these values should be summed/added together. For page_views, the value would be the total from the beginning of time up until now.
Current Table
+----+---------------+--------------+-----------------+-------+
| ID | TIMESTAMP | WEBSITE | METRIC_TYPE | VALUE |
+----+---------------+--------------+-----------------+-------+
| 1 | 1546610400000 | example1.com | page_views | 101 |
| 2 | 1546610401000 | example1.com | page_views | 117 |
| 3 | 1546610400000 | example1.com | unique_visitors | 30 |
| 4 | 1546610401000 | example2.com | page_views | 22 |
| 5 | 1546610401000 | example2.com | ad_referrals | 8 |
| 6 | 1546681000300 | example1.com | page_views | 206 |
+----+---------------+--------------+-----------------+-------+
Note for the above snippet: all timestamps are for 01/04/2019, except for row #6. I would like to create a SQL query to turn that table into the below view:
Desired View
+------------+--------------+------------+-----------------+--------------+
| DATE | WEBSITE | PAGE_VIEWS | UNIQUE_VISITORS | AD_REFERRALS |
+------------+--------------+------------+-----------------+--------------+
| 01/04/2019 | example1.com | 117 | 30 | NULL |
| 01/04/2019 | example2.com | 22 | NULL | 8 |
| 1/05/2019 | example1.com | 206 | NULL | NULL |
+------------+--------------+------------+-----------------+--------------+
I am aware of how to convert the timestamp into a date using DATE_FORMAT(FROM_UNIXTIME(floor(timestamp/1000))
and TIME(FROM_UNIXTIME(floor(timestamp/1000)))
.
What I need is to pivot these results, and only choose the latest record for each metric per day.
I have tried re-joining the table several times over, but am not close to the result I'm looking for (situation is with confidential data, so this data is for different metrics but in the same format).