在SQL中选择多个日期

时间:2018-03-13 23:33:44

标签: mysql sql

我的数据 table 如下:

 id    date1      date2        rate
 1     01/01/2017 03/01/2017   0.60
 1     02/01/2017 03/01/2017   0.40
 1     03/01/2017 03/01/2017   0.00
 1     04/01/2017 03/01/2017   0.00
 1     05/01/2017 03/01/2017   0.00
 2         .          .          .

对于每个ID,我想在 rate 变为0之前选择 date2 的最新正值。因此 03/01/3017 的值为 03/01/3017 ,值为 0.40 id {1}的费率在 date2 上变为0。我想选择费率为{{1}}的行。

我想为多个ID执行此操作。 {{1}}也不能成为一个周末。

2 个答案:

答案 0 :(得分:0)

我认为这将满足您的要求:

SELECT    a.*
FROM      data_table a
          INNER JOIN
(
    SELECT id
         , MIN(date1) AS date1
    FROM   data_table
    WHERE  rate > 0
    GROUP BY id
) b ON a.id = b.id
       AND a.date1 = b.date1;

答案 1 :(得分:0)

这是一种方法。我将表名称为table1

SELECT a.id, a.rate
FROM table1 a
WHERE a.date1 = (SELECT MAX(date1) FROM table1 WHERE a.id = id and rate <> 0)

table1包含您提供的数据以及由id = 2组成的2行数据。

数据

CREATE TABLE table1 (id INT, date1 DATE, date2 DATE, rate FLOAT);
INSERT table1(id, date1, date2, rate) VALUES
(1,'2017-01-01','2017-03-01',0.60),
(1,'2017-02-01','2017-03-01',0.40),
(1,'2017-03-01','2017-03-01',0.00),
(1,'2017-04-01','2017-03-01',0.00),
(1,'2017-05-01','2017-03-01',0.00),
(2,'2017-06-01','2017-03-01',0.30),
(2,'2017-07-01','2017-03-01',0.00);

<强> RESULT

id  rate
1   0.4
2   0.3

SQL Fiddle