我有一个表,在同一个表中保留多个不同的指标。度量值的值有一个“值”列,另一列用于标识度量的实际值。然后,我有一个纪元时间戳列,一个网站列和一个主键ID列。
我正在尝试创建一个MySQL视图,将每个度量标准显示为一个单独的列,并让每行代表每天每个度量标准的最新值(一天内可能有多个行用于一个度量标准,我想只显示当天最新时间的价值)。
编辑:值列只是给定时间的总计,因此这些值中的任何一个都不应该相加/加在一起。对于page_views,该值将是从开始到现在的总时间。
当前表
+----+---------------+--------------+-----------------+-------+
| 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 |
+----+---------------+--------------+-----------------+-------+
上述代码段的注释:所有时间戳均为01/04/2019,但第6行除外。我想创建一个SQL查询,将该表转换为下面的视图:
期望的视图
+------------+--------------+------------+-----------------+--------------+
| 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 |
+------------+--------------+------------+-----------------+--------------+
我知道如何使用DATE_FORMAT(FROM_UNIXTIME(floor(timestamp/1000))
和TIME(FROM_UNIXTIME(floor(timestamp/1000)))
将时间戳转换为日期。
我需要的是调整这些结果,并且只选择每天每个指标的最新记录。
我曾多次尝试重新加入该表,但我并不接近我正在寻找的结果(情况是机密数据,所以这些数据是针对不同的指标,但格式相同)。
您可以使用条件聚合,但需要过滤到每天的最后一行:
select date(FROM_UNIXTIME(floor(timestamp/1000)) as date, website,
max(case when metric_type = 'page_views' then value end) as page_views,
max(case when metric_type = 'unique_visitors' then value end) as unique_visitors,
max(case when metric_type = 'ad_referrals' then value end) as ad_referrals
from t
where t.timestamp = (select max(t2.timestamp)
from t t2
where date(FROM_UNIXTIME(floor(t2.timestamp/1000)) = date(FROM_UNIXTIME(floor(t.timestamp/1000)) and
t2.website = t.website and
t2.metric_type = t.metric_type
)
group by date, website;
您可以使用条件聚合
select DATE( FROM_UNIXTIME( floor(timestamp/1000) ) ) as date, website,
sum(case when metric_type = 'page_views' then value end) as page_views,
sum(case when metric_type = 'unique_visitors' then value end) as unique_visitors,
sum(case when metric_type = 'ad_referrals' then value end) as ad_referrals
from yourTable
group by date, website;
+------------+--------------+------------+-----------------+--------------+
| DATE | WEBSITE | PAGE_VIEWS | UNIQUE_VISITORS | AD_REFERRALS |
+------------+--------------+------------+-----------------+--------------+
| 01/04/2019 | example1.com | 218 | 30 | NULL |
| 01/04/2019 | example2.com | 22 | NULL | 8 |
| 01/05/2019 | example1.com | 206 | NULL | NULL |
+------------+--------------+------------+-----------------+--------------+