Mysql:获取日期的min和mx

时间:2016-03-31 15:07:12

标签: mysql

我有一个要求,我需要触发查询以检索from_date的最小值和to_date的最大值。我的数据如下:

+--------------------------------------+--------------------------------------+---------------------+---------------------+
| user_id                              | point_id                             |         from_date   | to_date             |
+--------------------------------------+--------------------------------------+---------------------+---------------------+
| 1e159ee9-0856-4ea8-88ab-4c0862f667af | c54c3bea-46e8-4377-bfa0-3a03c7abbafa | 2007-07-31 00:00:00 | 2012-04-08 00:00:00 |
| 1e159ee9-0856-4ea8-88ab-4c0862f667af | c54c3bea-46e8-4377-bfa0-3a03c7abbafa | 2012-04-09 00:00:00 | NULL                |
+--------------------------------------+--------------------------------------+---------------------+---------------------+

但是,当我触发以下查询时:

select min(from_date), max(to_date) from some_table where user_id='1e159ee9-0856-4ea8-88ab-4c0862f667af' and point_id ='c54c3bea-46e8-4377-bfa0-3a03c7abbafa' order by from_date;
+------------------------+----------------------+
| min(from_date)         | max(to_date) |
+------------------------+----------------------+
| 2007-07-31 00:00:00    | 2012-04-08 00:00:00  |
+------------------------+----------------------+

正如您所看到的,我希望结果中的to_date为NULL。但Max函数不会找我NULL。那么我有什么选择让我得到NULL?此外,to_date列可能不是NULL。在那种情况下,我需要NOT NULL正确的日期。有人可以帮忙吗?

2 个答案:

答案 0 :(得分:2)

SQL Fiddle

MySQL 5.6架构设置

CREATE TABLE some_table (
  user_id varchar(64),
  point_id varchar(64),
  from_date date,
  to_date date  
  );


  INSERT INTO some_table VALUES
  ('1e159ee9-0856-4ea8-88ab-4c0862f667af', 'c54c3bea-46e8-4377-bfa0-3a03c7abbafa', '2007-07-31 00:00:00', '2012-04-08 00:00:00'),
  ('1e159ee9-0856-4ea8-88ab-4c0862f667af', 'c54c3bea-46e8-4377-bfa0-3a03c7abbafa', '2012-04-09 00:00:00', NULL);

查询1

select min(from_date),
 case when MAX(to_date IS NULL) = 0 THEN max(to_date) END AS  max_to_date
from some_table
where user_id='1e159ee9-0856-4ea8-88ab-4c0862f667af' 
  and point_id ='c54c3bea-46e8-4377-bfa0-3a03c7abbafa'

<强> Results

|         min(from_date) | max_to_date |
|------------------------|-------------|
| July, 31 2007 00:00:00 |      (null) |

一些解释:

1-(to_date IS NULL)返回1或0

2- MAX(to_date IS NULL)将采用null值(如果存在)

3- MAX(NULL)= NULL,如果不是你应该在你的CASE / WHEN中放置一个ELSE

答案 1 :(得分:0)

尝试:

SELECT
  `der`.`min_from_date` `min(from_date)`,
  IF(`der`.`nulls` > 0, NULL, `der`.`max_to_date`) `max(to_date)`
FROM (
  SELECT
    MIN(`from_date`) `min_from_date`,
    MAX(`to_date`) `max_to_date`,
    SUM(IF(`to_date` IS NULL, 1, 0)) `nulls`
  FROM
    `some_table`
  WHERE
    `user_id` = '1e159ee9-0856-4ea8-88ab-4c0862f667af' AND
    `point_id` = 'c54c3bea-46e8-4377-bfa0-3a03c7abbafa'
  /*ORDER BY
    `from_date`*/
) `der`;