MySQL - 如何自动化从最近一天到前一天减去指标的视图查询&日期标记最新数据

时间:2017-07-05 21:23:07

标签: mysql mysql-workbench

我每天都有一个API调用,它为每天午夜的数据批次提供了唯一ID和日期戳的LIFETIME数据。这些数据被附加到MySQL中的数据库中,但是我需要以一种方式对其进行转换,以便为每个度量标准获取该唯一ID的每日数据。

MySQL中的我的表:

enter image description here

期望输出:

enter image description here

对于ID 3,我在前一天(2017年3月3日)和最近的日期(7/4/2017)之间取得了相应的指标(展示次数,点击次数)和时间戳记2017年7月4日。我需要通过id为多个ID和指标处理这种类型的转换。谢谢!

根据雅各布的反馈更新我的查询

CREATE VIEW `facebook_insights` AS  
SELECT  
  t1.id  
, t1.timestamp  
, t1.message  
, t1.posted  
, t1.permalink_url  
, t1.caption  
, t1.link  
, t1.type  
, t1.post_impressions - t2.post_impressions as Impressions  
, t1.post_impressions_organic - t2.post_impressions_organic as Post_Impressions_Organic  
, t1.post_impressions_paid - t2.post_impressions_paid as Post_Impressions_Paid  
, t1.post_engaged_users - t2.post_engaged_users as Post_Engaged_Users  
, t1.post_consumptions - t2.post_consumptions as Post_Consumptions  
, t1.post_negative_feedback - t2.post_negative_feedback as 
Post_Negative_Feedback  
, t1.post_negative_feedback_unique - t2.Post_Negative_Feedback_Unique as 
Post_Negative_Feedback_Unique  
, t1.post_impressions_fan - t2.post_impressions_fan as Post_Impressions_Fan  
, t1.post_impressions_fan_paid - t2.post_impressions_fan_paid as 
Post_Impressions_Fan_Paid  
, t1.post_engaged_fan - t2.Post_Engaged_Fan as Post_Engaged_Fan  
, t1.post_video_complete_views_organic - 
t2.post_video_complete_views_organic as Post_Video_Complete_Views_Organic  
, t1.post_video_complete_views_paid - t2.post_video_complete_views_paid as 
Post_Video_Complete_Views_Paid  
, t1.post_video_views_10s - t2.post_video_views_10s as Post_Video_Views_10s  
, t1.post_video_views_10s_unique - t2.post_video_views_10s_unique as 
Post_Video_Views_10s_Unique  
, t1.post_video_views_organic - t2.post_video_views_organic as 
Post_Video_Views_Organic  
, t1.post_video_views_paid - t2.post_video_views_paid as 
Post_Video_Views_Paid  
, t1.post_video_views_clicked_to_play - t2.post_video_views_clicked_to_play 
as Post_Video_Views_Clicked_to_Play  

FROM  
unpaid_media.facebook_insight t1  
JOIN unpaid_media.facebook_insight t2  
ON t1.id = t2.id   
and t1.timestamp  = t2.timestamp + INTERVAL 1 DAY  

2 个答案:

答案 0 :(得分:3)

这里的关键是重新加入表格。在下面的查询中,我正在重新加入您的表,但是将其设置为使得时间戳是连接上的限定符。这将加入前一天的记录,并允许您简单地减去它们。

select
  t1.id
  , t1.timestamp
  , t1.impressions - t2.impressions as impressions
  , t1.clicks - t2.clicks as clicks
from
  table t1
  join table t2
    on t1.id         = t2.id
    and t1.timestamp = t2.timestamp + INTERVAL 1 DAY

答案 1 :(得分:0)

看起来分组功能非常有用,因为您希望按日期和ID汇总展示次数和点击次数。此外,你没有提到这个数据需要任何连接(还),所以这是假设它在一个表中。下面是T-SQL:

USE DatabaseName
GO

SELECT T.ID, 
       (CAST(T.TimeStamp) as Date) as Date, 
       SUM(T.Impressions) as TotalImpressionsPerDay, 
       SUM(T.Clicks) as TotalClicksPerDay
FROM TableName as T
GROUP BY ID, (CAST(T.TimeStamp) as Date)
ORDER BY ID ASC