数据库
首页 > 数据库> > MySQL-如何自动执行将查询数据从最近日期减去到前一天的日期查询,并将日期戳记最新数据

MySQL-如何自动执行将查询数据从最近日期减去到前一天的日期查询,并将日期戳记最新数据

作者:互联网

我有一个每日API调用,可为我提供LIFETIME数据的唯一ID,并在每天的午夜为数据批打上日期戳.此数据被附加到MySQL中的数据库中,但是我需要对其进行转换,以便可以获取每个指标的唯一ID的每日数据.

我在MySQL中的表:

enter image description here

所需输出:

enter image description here

对于ID 3,我采用了前一天(2017/7/3)和最近日期(7/4/2017)的差异作为其各自的指标(展示次数,点击次数),并将该订单项时间戳记为7/4/2017.我需要针对多个ID和指标按ID处理这种类型的转换.谢谢!

根据Jacob的反馈更新我的查询:

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  

解决方法:

这里的关键是将表重新加入自身.在下面的查询中,我将重新连接您的表,但要对其进行设置,以使时间戳成为联接上的限定符.这将加入前一天的记录,并允许您简单地减去它们.

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

标签:mysql-workbench,mysql
来源: https://codeday.me/bug/20191111/2018168.html