我想获取包含相关日期列的列的最小值和最大值。下面是一个简单的表格示例和所需的输出。
ID SCORE DATE
1 100 1-1-2018
2 99 2-1-2018
3 102 3-1-2018
4 99 4-1-2018
5 98 5-1-2018
6 102 6-1-2018
7 100 7-1-2018
输出应为
MinValue MinDate MaxValue MaxDate
98 5-1-2018 102 6-1-2018
如果多次出现最小值或最大值,则应返回最后一个日期。
通过使用内部联接,我可以在一个查询中获得最小或最大值的适当日期,但不能同时获得两者。请参见下面的示例:
SELECT score as MinValue, date as MinDate
FROM table inner join (select min(score) from table ) x on table.score= x.score
ORDER BY date desc
LIMIT 1
这是一个sqlfiddle http://sqlfiddle.com/#!9/f50ced/4
能否在一个查询中提取所有必需的值?
答案 0 :(得分:1)
这是一种方法;不确定它是否最快。
Max
和Min
值。MaxValue
是MySQL中的Reserved Keyword;因此必须使用反引号(`)。尝试:
SELECT MIN(t1.minValue) AS minValue,
MAX(t2.Date) AS minDate,
MAX(t1.`maxValue`) AS `maxValue`,
MAX(t3.Date) AS maxDate
FROM
(
SELECT MIN(score) AS minValue,
MAX(score) AS `maxValue`
FROM your_table
) AS t1
JOIN your_table AS t2 ON t2.score = t1.minValue
JOIN your_table AS t3 ON t3.score = t1.`maxValue`
答案 1 :(得分:1)
您可以尝试以下方法:
select
@minv := (select min(SCORE) from tbl) as MinValue,
(select min(DATE) from tbl WHERE SCORE = @minv) as MinDate,
@maxv := (select max(SCORE) from tbl) as MxValue,
(select max(DATE) from tbl WHERE SCORE = @maxv) as MaxDate
;
结果如下:
+----------+----------+---------+----------+
| MinValue | MinDate | MxValue | MaxDate |
+----------+----------+---------+----------+
| 98 | 5-1-2018 | 102 | 6-1-2018 |
+----------+----------+---------+----------+