1

時間間隔を定義するテーブルがあります。

 _______________________________
| id | description | start_date |
|____|_____________|____________|
|  1 | First       |    NULL    |
|  3 | Third       | 2009-12-18 |
|  5 | Second      | 2009-10-02 |
|  4 | Last        | 2009-12-31 |
|____|_____________|____________|

開始日のみを格納し、終了日は次の日の前日です。

次の結果が欲しいです:

 ____________________________________________
| id | description | start_date |  end_date  |
|____|_____________|____________|____________|
|  1 | First       |    NULL    | 2009-10-01 |
|  5 | Second      | 2009-10-02 | 2009-12-17 |
|  3 | Third       | 2009-12-18 | 2009-12-30 |
|  4 | Last        | 2009-12-31 |    NULL    |
|____|_____________|____________|____________|

行には他の行の値が含まれているため、このクエリをどのように作成すればよいですか?

DATE_SUB(MySQL関数が役立つと思います。)

4

4 に答える 4

2

試す

select id, description, start_date, end_date from
  (
    select @rownum_start:=@rownum_start+1 rank, id, description, start_date
    from inter, (select @rownum_start:=0) p
    order by start_date
  ) start_dates
left join
  (
    select @rownum_end:=@rownum_end+1 rank, start_date - interval 1 day as end_date
    from inter, (select @rownum_end:=0) p
    where start_date is not null
    order by start_date
  ) end_dates
using (rank)

あなたのテーブルはどこinterですか

これは実際には次のようになります。

mysql> select id, description, start_date, end_date from ...
+----+-------------+------------+------------+
| id | description | start_date | end_date   |
+----+-------------+------------+------------+
|  1 | First       | NULL       | 2009-10-01 |
|  5 | Second      | 2009-10-02 | 2009-12-17 |
|  3 | Third       | 2009-12-18 | 2009-12-30 |
|  4 | Last        | 2009-12-31 | NULL       |
+----+-------------+------------+------------+
4 rows in set (0.00 sec)
于 2009-12-18T18:50:06.377 に答える
2
SELECT d.id, d.description, MIN(d.start_date), MIN(d2.start_date) - INTERVAL 1
DAY AS end_date
FROM start_dates d
LEFT OUTER JOIN start_dates d2 ON ( d2.start_date > d.start_date OR d.start_date IS NULL )
GROUP BY d.id, d.description
ORDER BY d.start_date ASC
于 2009-12-18T18:54:37.003 に答える
0

PHPを使用している場合は、スクリプトで前の日付を計算するだけです。それは簡単です。

そうでない場合は、次のようになります。

SELECT ID,description,start_date,start_date-1 AS end_date FROM ...

仕事?

更新:開始日2009-12-25に対して20091224を返すため、部分的に機能しますが、2009-12-01などの日付に対しては機能しません。

于 2009-12-18T18:37:47.960 に答える
0

試す

   Select d.Id, d.Description, d.Start_Date, 
       n.Start_Date - 1 EndDate
   From Table d 
     Left Join Table n
        On n.Start_Date = 
              (Select Min(Start_date)
               From Table
               Where Start_Date > Coalesce(d.Start_Date, '1/1/1900')
于 2009-12-18T18:43:21.397 に答える