[英]SQl query - 2 highest values for each group and second must be “younger” then first
I have MySQL table. 我有MySQL表。 I need select two highest values for each group, but second highest value can`t be "more recent".
我需要为每个组选择两个最大值,但是第二个最大值不能是“较新的”。 If the highest value for Project 1 is date '2015-12-01', the second highest value must be earlierl then '2015-12-01'.
如果项目1的最高值是日期“ 2015-12-01”,则第二个最高值必须早于“ 2015-12-01”。 This date is user input within application, eg.: user input date '2014-01-03' and get 2 highest value order by date.
该日期是用户在应用程序中输入的日期,例如:用户输入日期“ 2014-01-03”,并按日期获得2个最高价值订单。
'2013-10-11' - 480 viists '2013-10-11'-480人
+ --------- + ----------- + ---------+ | project | visits | date | + --------- + ----------- + ---------+ | 1 | 750 |2015-12-01| | 1 | 582 |2014-11-01| | 1 | 423 |2013-10-02| | 2 | 666 |2016-01-01| | 2 | 812 |2012-02-02| | 2 | 450 |2014-03-05| + --------- + ----------- + -------- +
Edit: I try this (it is more complex then example above) + join table due to ProjectName 编辑:我尝试此(它比上面的示例更复杂)+由于ProjectName的联接表
set @num := 0, @group := '';
select ProjectName,visits, date
from
(
select date, Projects_ID, visits,
@num := if(@group = `Projects_ID`, @num + 1, 1) as row_number,
@group := Projects_ID as col
from Hits
where date < '2016-01-11' and visits > 0
order by Projects_ID,date, visits desc
) as x inner join Projects as p on x.Projects_ID =
p.ID
where x.row_number <= 2
group by ProjectName,Projects_ID, date
I got table where was the highest value, but in some cases second highest value was "most recent" then highest value. 我得到了最高价值所在的表格,但在某些情况下,第二高价值是“最近”,然后是最高价值。
SELECT a.visits, a.project, a.date
FROM temper1 AS a
WHERE (SELECT COUNT(*)
FROM temper1 AS b
WHERE b.project = a.project AND b.date >= a.date
) <= 2
ORDER BY a.visits ASC, a.date DESC
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.