sql找到满足某些条件的最小值

时间:2016-06-16 09:11:15

标签: sql postgresql

我有一张桌子,我希望在特定列的值最小且时间在9:15到10:00之间时获取行。

这是我的代码

<!DOCTYPE html>
<html>

<head>

</head>

<body>
    <div id="loginpending" class="">
        <a href="login.html">Signup</a>/<a href="login.html">Login</a> here!
    </div>
    <div id="loggedin" class="hidden">
        Hello!
    </div>
    <button id="button" onclick="">Hello!</button>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
    <script type="text/javascript" src="sample.js"></script>
</body>

</html>

我希望得到类似的东西:

Select time, size, sym, price FROM test WHERE 
price = (Select MIN(price) from 
(select time, size, price from test where sym = 'PTX' And date = '2014-01-02' And time >=  '9:15'  And time <'10:00'  ) as test1
)
Group By sym, time, size, price;

相反,我正在

     time     |  size  | sym  | price 
--------------+--------+------+-------
 9:53:32.486 |    100 | PTX  |  2.42

2 个答案:

答案 0 :(得分:1)

您需要将主查询中的WHERE与子查询匹配。目前,您正在查找条件的最低价格,但未对主查询应用相同的条件。试试这个:

Select time, size, sym, price FROM test WHERE 
price = (Select MIN(price) from 
(select time, size, price from test where sym = 'PTX' And date = '2014-01-02' And time >=  '9:15'  And time <'10:00'  ) as test1
) and sym = 'PTX' And date = '2014-01-02' And time >=  '9:15'  And time <'10:00'
Group By sym, time, size, price;

答案 1 :(得分:0)

一种方法只使用order by并将结果限制为一行:

Select time, size, sym, price
from test 
where sym = 'PTX' And date = '2014-01-02' And time >= '9:15' And time < '10:00'
order by price
limit 1;

注意:某些数据库将limit拼写为fetch first 1 row only,在top 1中使用select,或者使用类似的方法来限制返回的行数。