1

家が頻繁に塗装されるとしましょう。単純なテーブルで変更 (「塗装」イベント) を追跡します。

 _______________________
/ PaintDate | NewColor  \
|-----------|-----------|
| 1/2/2012  |  Red      |
| 3/5/2013  |  Blue     |
| 9/9/2013  |  Green    |
\___________|___________/

家が特定の色にあった日付範囲のテーブルを提供できる SELECT ステートメントはありますか?

望ましい出力:

 _______________________________
/  From    |   To     |  Color  \
|----------|----------|---------|
| 1/2/2012 | 3/5/2013 |   Red   |
| 3/5/2013 | 9/9/2013 |   Blue  |
| 9/9/2013 | NULL     |   Green | -- Not repainted yet, the date in the 'To' column should be NULL
\__________|__________|_________/
4

2 に答える 2

2

Well you can use this query

SELECT 
  p.PaintDate AS `From`,
  l.PaintDate AS `TO`,
  p.NewColor AS `Color` 
FROM
  paint AS p 
  LEFT JOIN 
    (SELECT * FROM paint LIMIT 1, 18446744073709551615) AS l   
    ON l.PaintDate = (SELECT PaintDate FROM paint WHERE PaintDate > p.PaintDate ORDER BY PaintDate ASC LIMIT 1)

OUTPUT

From       |    TO          | Color
-------------------------------
2012-02-01 |    2012-05-03  | Red
2012-05-03 |    2013-09-09  | Blue
2013-09-09 |    (NULL)      | Green

Demo

The above query can be improved like this

SELECT 
  p.PaintDate AS `From`,
  l.PaintDate AS `TO`,
  p.NewColor AS `Color` 
FROM
  paint AS p 
  LEFT JOIN paint AS l ON l.PaintDate = (SELECT PaintDate FROM paint WHERE PaintDate > p.PaintDate ORDER BY PaintDate ASC  LIMIT 1)

Demo

于 2013-02-12T12:42:13.233 に答える
0
SELECT  aa.PaintDate `FROM`, bb.PaintDate `TO`,
        aa.NewColor
FROM    
        (
            SELECT  @row:=@row+1 as RankNo,
                    a.PaintDate,
                    a.NewColor
            FROM    tableName a, (SELECT @row:=0) b
            ORDER   BY a.PaintDate
        ) aa
        LEFT JOIN
        (
            SELECT  @row2:=@row2+1 as RankNo,
                    a.PaintDate
            FROM    tableName a, (SELECT @row2:=0) b
            ORDER   BY a.PaintDate
        ) bb ON aa.RankNo+1 = bb.RankNo
于 2013-02-12T12:43:41.570 に答える