在sqlite3中选择max,min函数无法获得正确的结果

时间:2017-01-23 01:43:59

标签: sql sqlite

我有这张桌子:

CREATE TABLE data ( 
    timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
    channel   INTEGER  DEFAULT '0',
    raw_Value REAL     DEFAULT '0',
    modify    REAL     DEFAULT '0' 
);

我可以使用此查询获得正确的结果

SELECT 
   (SELECT TIMESTAMP
      WHERE value=
      (SELECT max(value))) AS maxDate
FROM
      (SELECT *,raw_value AS value
         FROM DATA
         WHERE TIMESTAMP>='2017-01-23 00:00:00'
         AND TIMESTAMP<'2017-01-24 00:00:00'
         AND channel=0);

结果是:

maxDate
-------------------
2017-01-23 16:47:00

但是当我使用这个查询时,我有一个(null)结果

SELECT 
  (SELECT TIMESTAMP
     WHERE value=
     (SELECT max(value))) AS maxDate,

  (SELECT TIMESTAMP
     WHERE value=
     (SELECT min(value))) AS minDate
FROM
  (SELECT *,raw_value AS value
     FROM DATA
   WHERE TIMESTAMP>='2017-01-23 00:00:00'
   AND TIMESTAMP<'2017-01-24 00:00:00'
   AND channel=0);

结果是:

maxDate     minDate
----------  -------------------
            2017-01-23 12:32:00

当我使用此查询时,只是更改了顺序:

SELECT 
  (SELECT TIMESTAMP
     WHERE value=
     (SELECT min(value))) AS minDate,

  (SELECT TIMESTAMP
     WHERE value=
     (SELECT max(value))) AS maxDate


FROM
  (SELECT *,raw_value AS value
     FROM DATA
   WHERE TIMESTAMP>='2017-01-23 00:00:00'
   AND TIMESTAMP<'2017-01-24 00:00:00'
   AND channel=0);

现在我明白了:

minDate     maxDate
----------  -------------------
            2017-01-23 16:47:00

我想念一下吗?

1 个答案:

答案 0 :(得分:0)

如何加入和group by

SELECT t.timestamp, t.value
FROM (SELECT value, MIN(TIMESTAMP) as min_timestamp, MAX(TIMESTAMP) as max_TIMESTAMP
      FROM DATA
      WHERE TIMESTAMP >= '2017-01-23 00:00:00' AND
            TIMESTAMP < '2017-01-24 00:00:00' AND
            channel = 0
     ) tt JOIN
     DATA t
     ON t.TIMESTAMP IN (min_timestamp, max_timestamp)
WHERE t.channel = 0;