“复杂”MySql请求,在同一请求中获取与MIN和MAX值相关联的一些列

时间:2013-11-17 08:10:00

标签: mysql sql

例如,我有一个数据集如下:

id, idPro, mesure2, mesure3, date
'6067', '1', '9.0', '29.3', '2013-11-17 12:48:39'
'6061', '1', '7.3', '30.3', '2013-11-17 15:20:12'
'6068', '2', '7.0', '29.3', '2013-11-17 12:48:39'
'6062', '2', '9.0', '25.3', '2013-11-17 15:20:12'
'6069', '3', '7.6', '29.0', '2013-11-17 12:48:39'
'6063', '3', '7.5', '27.0', '2013-11-17 15:20:12'
'6070', '4', '8.9', '29.1', '2013-11-17 12:48:39'
'6064', '4', '9.1', '23.1', '2013-11-17 15:20:12'
'6071', '5', '9.4', '28.9', '2013-11-17 12:48:39'
'6065', '5', '5.4', '30.9', '2013-11-17 15:20:12'
'6072', '6', '9.3', '28.9', '2013-11-17 12:48:39'
'6066', '6', '9.1', '24.9', '2013-11-17 15:20:12'

我想输出一个具有最小和最大值" mesure2"和" mesure3"按idPro + Date分组,以及出现最小值和最大值的时间。 所以它应该输出如下内容:

idPro, mesureMin, dateMinMesure, mesureMax, timeMaxMesure, mesureType, date
'1', '7.3', '2013-11-17 12:48:39', '9.0', '2013-11-17 12:48:39', 'mesure2', '2013-11-17'
'1', '29.3', '2013-11-17 12:48:39', '30.3', '2013-11-17 15:20:12', 'mesure3', '2013-11-17'
'2', '7.0', '2013-11-17 12:48:39', '9.0', '2013-11-17 15:20:12', 'mesure2', '2013-11-17'
'2', '29.3', '2013-11-17 12:48:39', '25.3', '2013-11-17 15:20:12', 'mesure3', '2013-11-17'
...

实际上,我发出一个请求,为每个mesure类型(mesure2或mesure3)输出每天的最小值和最大值,然后我做其他请求来获取每个mesure的日期。 (我使用php,我用它构建请求  WHERE mesure2 = $valueReturnedByTheFirstRequest AND date LIKE '%2013-11-17%' ) 但这是很多sql请求,我正在寻找一种在1个查询中输出类似内容的方法。

提前致谢

1 个答案:

答案 0 :(得分:1)

尝试此查询:

SELECT date,
       idpro,
       mesureType,
       mesureMin,
       ( SELECT min(t.date) FROM table1 t
         WHERE mesure2 = mesureMin
             AND t.idpro = x1.idpro
             AND x1.date = date( t.date )
        ) dateMinMesure ,
       mesureMax,
       ( SELECT min(t.date) FROM table1 t
         WHERE mesure2 = mesureMax
             AND t.idpro = x1.idpro
             AND x1.date = date( t.date )
        ) dateMaxMesure 
FROM( 
  SELECT date(date) `date`,
         idpro,
         'measure2' mesureType,
         min( mesure2 ) mesureMin,
         max( mesure2 ) mesureMax
  FROM table1 
  GROUP BY date(date), idpro, mesureType
) x1
UNION ALL
SELECT date,
       idpro,
       mesureType,
       mesureMin,
       ( SELECT min(t.date) FROM table1 t
         WHERE mesure3 = mesureMin
             AND t.idpro = x1.idpro
             AND x1.date = date( t.date )
        ) dateMinMesure ,
       mesureMax,
       ( SELECT min(t.date) FROM table1 t
         WHERE mesure3 = mesureMax
             AND t.idpro = x1.idpro
             AND x1.date = date( t.date )
        ) dateMaxMesure 
FROM( 
  SELECT date(date) date,
         idpro,
         'measure3' mesureType,
         min( mesure3 ) mesureMin,
         max( mesure3 ) mesureMax
  FROM table1 
  GROUP BY date(date), idpro, mesureType
) x1
ORDER BY date, idpro, mesuretype

演示 - > http://www.sqlfiddle.com/#!2/daa51/14