我想查找两列的第一个和最后一个值以及我的查询

时间:2016-10-07 19:27:19

标签: mysql sql

SELECT Min(`low`), 
       Max(`high`), 
       `snapshotdatetime` 
FROM   `historical_intraday_price` 
WHERE  Unix_timestamp(`snapshotdatetime`) >= Unix_timestamp('2016-09-01 09:20:00.000000 ') 
GROUP  BY Unix_timestamp(`snapshotdatetime`) DIV 180 

这是我的查询我希望字段名称的第一个值打开,字段名称的最后一个值使用此查询关闭。 它的smthng喜欢

SELECT First(`open`), 
       Last(`close`), 
       Min(`low`), 
       Max(`high`), 
       `snapshotdatetime` 
FROM   `historical_intraday_price` 
WHERE  Unix_timestamp(`snapshotdatetime`) >= Unix_timestamp('2016-09-01 09:20:00.000000     ') 
GROUP  BY Unix_timestamp(`snapshotdatetime`) DIV 180 

但FIRST(Open),LAST(Close)将无效,任何人都有任何想法,请帮助

1 个答案:

答案 0 :(得分:-1)

也许使用UNION?像这样的东西?

SELECT MAX(open), MAX(close), MIN(low), MAX(high), MAX(snapshotDateTime)
FROM (
    SELECT `open`, NULL AS close, MIN(`low`) AS low, MAX(`high`) AS high, `snapshotDateTime`
    FROM table
    WHERE [condition(s)]
    GROUP BY `snapshotDateTime`
    ORDER BY `snapshotDateTime`
    LIMIT 1
    UNION ALL 
        SELECT NULL, `close`, MIN(`low`), MAX(`high`), `snapshotDateTime`
        FROM table
        WHERE [condition(s)]
        GROUP BY `snapshotDateTime`
        ORDER BY `snapshotDateTime` DESC
        LIMIT 1
    ) U