繁体   English   中英

在SQL中请求带有日期的多列最小值/最大值

[英]Request multi column min/max with date in SQL

我有一个SQL表,看起来像:

Date        temp    dewpoint    humidity
10/12/15    5.1     2.4         57
11/12/15    4.1     5.8         69
12/12/15    20.6    3.6         56
13/12/15    13.0    2.5         21
14/12/15    5.6     13.6        15
15/12/15    5.1     2.4         56

我想知道有可能只用一个SQL查询就可以打印出来。 也就是说,对于每个数据列,获取带有发生日期的最小值和最大值(例如,我想知道最小值4.1在11/12/15上,最大值是20.6在15/12/12上。)

可以通过一个sql查询来做到这一点吗? 具体来说,我希望输出格式为:

Date        dataName     dataValue
11/12/15    temp-min     4.1
12/12/15    temp-max     20.6
14/12/15    humidity-min 15
11/12/15    humidity-max 69

正是您想要接收的东西,但是看起来很糟糕。

SELECT date, 'temp-min' dataName, temp dataValue
FROM numbers WHERE temp = (SELECT min(temp) FROM numbers)
UNION
SELECT date, 'temp-max' dataName, temp dataValue
FROM numbers WHERE temp = (SELECT max(temp) FROM numbers)
UNION
SELECT date, 'humidity-min' dataName, humidity dataValue
FROM numbers WHERE humidity = (SELECT min(humidity) FROM numbers)
UNION
SELECT date, 'humidity-max' dataName, humidity dataValue
FROM numbers WHERE humidity = (SELECT max(humidity) FROM numbers)
;

您可以使用单个查询轻松完成此操作:

SELECT Date, max(temp), min(temp), max(dewpoint), min(dewpoint), etc...
FROM yourtable
GROUP BY Date

以获得最小/最大的多列结果。 但是在MySQL中,很难将结果“取消透视”为单列/多行结果。 这种转换最好在客户端代码中完成。

在MySQL中,最简单的方法可能是使用substring_index() / group_concat()技巧:

select substring_index(group_concat(date order by temp asc), ',', 1) as minTempDate,
       substring_index(group_concat(date order by temp desc), ',', 1) as maxTempDate,
       substring_index(group_concat(date order by dewpoint asc), ',', 1) as minDPDate,
       substring_index(group_concat(date order by dewpoint desc), ',', 1) as maxDPDate,
       substring_index(group_concat(date order by humidity asc), ',', 1) as minHumidityDate,
       substring_index(group_concat(date order by humidity desc), ',', 1) as maxHumidityDate
from table t;

一种替代方法是使用union all像这样:

(select date, 'temp-min', temp from table t order by temp asc limit 1)
union all
(select date, 'temp-max', temp from table t order by temp desc limit 1)
union all
(select date, 'humidity-min', humidity from table t order by humidity asc limit 1)
union all
(select date, 'humidity-max', humidity from table t order by humidity desc limit 1)

暂无
暂无

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

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