简体   繁体   English

选择最大日期之和

[英]select sum of max date

I have some sites that I collect analytics data from, each site has data for every country, not all the sites get data every month. 我有一些网站,我从中收集分析数据,每个网站都有每个国家/地区的数据,而不是所有网站每个月都会获取数据。

I'd like to get the sum total of visits from all the sites in their last set of data (which may not have the same date). 我想得到他们最后一组数据中所有网站的访问总和(可能没有相同的日期)。

I can't use MAX() in the where clause as that's invalid. 我不能在where子句中使用MAX(),因为它是无效的。

I've tried storing the last date as a variable but that doesn't work: 我已经尝试将最后一个日期存储为变量,但这不起作用:

select sites.id, sites.name, SUM(data.visits), @start := MAX(data.start_date)
inner join data on data.profile_id = sites.profile_id
where data.start_date = @start
group by sites.profile_id

I've also played around with sub queries but just not quite got it right yet. 我也玩过子查询,但还没有完全正确。

Use a subquery to get the max date and join that in: 使用子查询获取最大日期并将其加入:

select sites.id, sites.name, SUM(data.visits), dp.maxdate
from sites inner join
     data
     on data.profile_id = sites.profile_id inner join
     (select profile_id, MAX(start_date) as maxdate
      from data
      group by profile_id
     ) dp
     on data.profile_id = dp.profile_id and data.start_date = dp.maxdate
group by sites.profile_id, sites.name, dp.maxdate

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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