MySQL语句的两行之间存在差异

时间:2013-02-13 15:37:10

标签: mysql select inner-join

我试图在mysql数据库中区分两行 我有这个表包含ID,公里,日期,car_id,car_driver等...
由于我并不总是按照正确的顺序输入表格中的信息,我最终可能会得到这样的信息:

ID | Kilometers | date | car_id | car_driver | ...
 1 | 100        | 2012-05-04 | 1 | 1  
 2 | 200        | 2012-05-08 | 1 | 1
 3 | 1000       | 2012-05-25 | 1 | 1 
 4 | 600        | 2012-05-16 | 1 | 1

使用select语句,我能够正确地对表进行排序:

SELECT * FROM mytable ORDER BY car_driver ASC, car_id ASC, date ASC

我会得到这个:

ID | Kilometers | date  | car_id | car_driver | ...  
 1 | 100        | 2012-05-04 | 1 | 1  
 2 | 200        | 2012-05-08 | 1 | 1
 4 | 600        | 2012-05-16 | 1 | 1  
 3 | 1000       | 2012-05-25 | 1 | 1

现在我想查看基本上我有这些额外信息的地方:自上次约会以来的公里数,我希望获得这样的信息:

ID | Kilometers | date       | car_id | car_driver | number_km_since_last_date   
 1 | 100        | 2012-05-04 | 1 | 1 | 0  
 2 | 200        | 2012-05-08 | 1 | 1 | 100  
 4 | 600        | 2012-05-16 | 1 | 1 | 400  
 3 | 1000       | 2012-05-25 | 1 | 1 | 400

我想做一个INNER JOIN来执行我想要的东西,但我感觉我无法加入我的ID,因为它们没有正确排序。
有没有办法实现我想要的?

我应该创建一个带有row_number的视图,然后我可以在我的INNER JOIN中使用它吗?

5 个答案:

答案 0 :(得分:18)

SELECT
    mt1.ID,
    mt1.Kilometers,
    mt1.date,
    mt1.Kilometers - IFNULL(mt2.Kilometers, 0) AS number_km_since_last_date   
FROM
    myTable mt1
    LEFT JOIN myTable mt2
        ON mt2.Date = (
            SELECT MAX(Date)
            FROM myTable mt3
            WHERE mt3.Date < mt1.Date
        )
ORDER BY mt1.date

Sql Fiddle

或者,通过MySql hackiness模仿lag()函数......

SET @kilo=0;

SELECT
    mt1.ID,
    mt1.Kilometers - @kilo AS number_km_since_last_date,
    @kilo := mt1.Kilometers Kilometers,
    mt1.date
FROM myTable mt1
ORDER BY mt1.date

Sql Fiddle

答案 1 :(得分:3)

在Postgres,Oracle和SQL-Server 2012中,这很简单,使用LAG()函数:

SELECT
    id, kilometers, date,
    kilometers 
    - COALESCE( LAG(kilometers) OVER (ORDER BY date ASC, car_driver ASC, id ASC)
              , kilometers) 
        AS number_km_since_last_date
FROM
    mytable ;

在MySQL中,我们必须做一些讨厌的结构。内联子查询(性能可能不是很好):

SELECT
    id, kilometers, date,
    kilometers - COALESCE(
            ( SELECT p.kilometers
              FROM mytable AS p
              WHERE ( p.date = m.date AND p.car_driver = m.car_driver
                                                     AND p.id < m.id
                   OR p.date = m.date AND p.car_driver < m.car_driver
                   OR p.date < m.date
                    )
              ORDER BY p.date DESC, p.car_driver DESC
                  LIMIT 1
            ), kilometers) 
        AS number_km_since_last_date
FROM
    mytable AS m ;

或自我加入(已由@Michael Fredrickson提供)或使用MySQL变量(已经提供)。


如果您希望计数器从每个car_id的0开始,这将在许多其他DBMS中使用PARTITION BY完成:

SELECT
    id, kilometers, date,
    kilometers 
    - COALESCE( LAG(kilometers) OVER (PARTITION BY car_id 
                                      ORDER BY date ASC, car_driver ASC, id ASC)
              , kilometers) 
        AS number_km_since_last_date
FROM
    mytable ;

它可以在MySQL中完成:

SELECT
    id, kilometers, date,
    kilometers - COALESCE(
            ( SELECT p.kilometers
              FROM mytable AS p
              WHERE p.car_id = m.car_id
                AND ( p.date = m.date AND p.car_driver = m.car_driver
                                                     AND p.id < m.id
                   OR p.date = m.date AND p.car_driver < m.car_driver 
                   OR p.date < m.date
                    )
              ORDER BY p.date DESC, p.car_driver DESC
                  LIMIT 1
            ), kilometers) 
        AS number_km_since_last_date
FROM
    mytable AS m ;

答案 2 :(得分:0)

如果数据未排序,我只能想到内联子查询(在大表上不是一个好主意):

select t1.*,
t1.Kilometers - (select top 1 kilometers from mytable t2 where t2.date < t1.date order by t2.date desc) as number_km_since_last_date
from mytable t1

如果您获得数据排序,则可以使用左连接

select t1.*
t1.Kilometers - t2.Kilometers as number_km_since_last_date
from mytable t1
left join mytable t2
  on t1.id = t2.id + 1

你可能会说我更像是一个TSQL人,所以你可能需要调整MySQL的语法。

答案 3 :(得分:0)

以下是使用CURSOR作为此用例的示例

CREATE TABLE TEMP1
(
    MyDate DATETIME,
    MyQty INT
)

INSERT INTO TEMP1 VALUES ('01/08/17', 100)
INSERT INTO TEMP1 VALUES ('01/09/17', 120)
INSERT INTO TEMP1 VALUES ('01/10/17', 180)

DECLARE @LastDate DATETIME = NULL
DECLARE @LastQty INT = NULL
DECLARE @MyDate DATETIME = NULL
DECLARE @MyQty INT = NULL

DECLARE mycursor CURSOR FOR
SELECT MyDate, MyQty FROM TEMP1 ORDER BY MyDate
OPEN mycursor
FETCH NEXT FROM mycursor INTO @MyDate, @MyQty

WHILE @@FETCH_STATUS = 0  
BEGIN  

    SELECT @MyDate, @MyQty - @LastQty

    SET @LastDate = @MyDate
    SET @LastQty = @MyQty

FETCH NEXT FROM mycursor INTO @MyDate, @MyQty
END

CLOSE mycursor
DEALLOCATE mycursor

答案 4 :(得分:0)

在MySQL 8中,您可以使用CTE和ROW_NUMBER窗口函数进行更具可读性的查询

WITH cte_name AS (
    SELECT
    ROW_NUMBER() OVER (ORDER BY update_time) as row_num,
    id,
    other_data,
    update_time
    FROM table_name WHERE condition = 'some_condition'
)
SELECT t2.id, t2.other_data, TIMEDIFF(t2.update_time, t1.update_time) AS time_taken
FROM
cte_name t1
JOIN cte_name t2 ON t1.row_num = t2.row_num-1
ORDER BY time_taken;

在此示例中,我尝试获取日期时间值之间的差异。

  • 想法是使用ROW_NUMBER窗口函数在按update_time排序后为每行分配一个增量编号。
  • CTE允许我们编写子查询,而不必重复编写相同的代码。
  • 我们自己加入CTE。联接条件基本上是-第二个子查询的每个nᵗʰ项与第一个子查询的n-1ᵗʰ项联接(这也意味着第一行将从结果集中消失。如果需要,可以使用UNION来添加第一行)。

有一些很好的教程可用于: CTE (Common Table Expression)ROW_NUMBER甚至window functions