我的数据库中有一个表格,如下所示: ID | datetime | value1 | value2 |值3
现在我想选择datetime,value1,value2和value3,其中value1是每天最低(MIN(value1))。下面的示例(箭头指示需要选择的行):
ID | datetime | value1 | value2 | value3
1 | 2014-01-01 00:06:00 | 10 | 15 | 20
2 | 2014-01-01 00:12:00 | 5 | 15 | 22 <--
3 | 2014-01-01 00:18:00 | 12 | 45 | 25
4 | 2014-01-02 00:06:00 | 1 | 25 | 10 <--
5 | 2014-01-02 00:12:00 | 12 | 45 | 25
6 | 2014-01-02 00:18:00 | 13 | 25 | 10
7 | 2014-01-03 00:06:00 | 17 | 35 | 95
8 | 2014-01-03 00:12:00 | 15 | 75 | 10
9 | 2014-01-03 00:18:00 | 12 | 75 | 35 <--
我有以下查询:
SELECT
datetime,
MIN(value1) as value1,
value2,
value3
FROM
table
GROUP BY
DAY(datetime)
ORDER BY
datetime ASC
LIMIT 50
这给了我一个结果,但不是我所期待的。 datetime和value2,value3不是来自找到每日最小值的行。
有人可以解释一下我做错了吗?
此外:我能够将这个(与selfjoin或其他东西)组合在一起,我会得到上面那天的最小值,然后从结果集中我只选择其中的行,例如value2&gt ; 20&amp;&amp; value2&lt; 60&amp;&amp; value3&gt; 10?
非常感谢提前
答案 0 :(得分:1)
select
*
from
Table1 t
inner join (select date(datetime) as dt, min(value1) v from Table1 group by dt) st
on date(t.datetime) = st.dt and t.value1 = st.v
看到它在 sqlfiddle
在本手册中查看更多示例:The Rows Holding the Group-wise Maximum of a Certain Column
答案 1 :(得分:0)
试试这个,
SELECT
datetime,
MIN(value1) as value1,
value2,
value3
FROM
table
GROUP BY
DAY(datetime)
ORDER BY
value1 ASC
LIMIT 50
答案 2 :(得分:0)
试试这个,
select t1.datentime, t1.value1, value2, value3
from test t1, ( select date(datentime) datentime,min(value1) value1
from test
group by date(datentime)) dummy
where date(t1.datentime)=dummy.datentime and t1.value1=dummy.value1
此处正在运作SQLFiddle