我有一个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是在2015年12月12日,最大值是20.6 / 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
答案 0 :(得分:1)
这正是你想要收到的,但它看起来很糟糕。
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)
;
答案 1 :(得分:0)
您只需一个查询即可轻松完成:
SELECT Date, max(temp), min(temp), max(dewpoint), min(dewpoint), etc...
FROM yourtable
GROUP BY Date
获取最小值/最大值的多列结果。但是在MySQL中很难将结果“取消”到单列/多行结果中。这种转换最好在客户端代码中完成。
答案 2 :(得分:0)
在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)