Mysql行之间的区别

时间:2016-03-04 10:12:56

标签: mysql sql

我希望通过以下数据获得2排汽车的价格差异。 我想将价格列ex:(200-100),(300-200)等作为数据

我的表:

enter image description here

My desired output:

我尝试了什么

select t1.row_num1,t1.car_name
from
(
    select (@row_num := @row_num +1) as row_num1 ,(select @row_num =0) r1, car_name,price  
    from car
)t1

我知道我没有id列。因此我生成了row_number。 现在我有问题自己加入这张桌子并获得不同。 你的帮助很明显。

3 个答案:

答案 0 :(得分:1)

虽然你的输出似乎令人困惑,但我给出了以下答案:

SOLUTION #1

SELECT 
carsTable1.car_name,
carsTable1.price,
CASE WHEN ABS(carsTable1.price - (SELECT price FROM cars WHERE car_name='car 2')) = 0 THEN NULL ELSE 
        ABS(carsTable1.price - (SELECT price FROM cars WHERE car_name='car 2')) END diff
FROM
(SELECT 
    @rn := @rn + 1 row_number,
    cars.car_name,
    cars.price 
FROM cars, (SELECT @rn := 0) var
) carsTable1;

Demo Here

示例输入:

car_name   price 

car 1       100

car 2       200

car 3       300

示例输出:

    car_name   price     diff

    car 1       100      100

    car 2       200      NULL

    car 3       300      100

注意: car 2的价格与其他汽车的价格进行比较。因此结果显示nullcar 2,因为它是参考车。

如果我误解了你的要求那么它必须是:你想要连续行之间的价格差异,即 (No car,car1),(car1,car2), (car2,car3), (car3,car4)....

因此,在这种情况下,您可以采用以下查询:

SOLUTION #2

SELECT 
car_name,
cars.price,
CASE WHEN @currentPrice = 0 THEN NULL ELSE ABS(cars.price - @currentPrice) END AS diff,
@currentPrice := price
FROM cars ,(SELECT @currentPrice := 0) var
ORDER BY car_name

SQL FIDDLE BASED ON THIS QUERY

如果你想要omit the fourth column

SELECT 
t.car_name,
t.price,
t.diff
FROM 
(
    SELECT 
    car_name,
    cars.price,
    CASE WHEN @currentPrice = 0 THEN NULL ELSE (cars.price - @currentPrice) END AS diff,
    @currentPrice := price
    FROM cars ,(SELECT @currentPrice := 0) var
    ORDER BY car_name ) t

SQL FIDDLE BASED ON THIS QUERY

答案 1 :(得分:1)

试试这个

set @next_row_price := null;
SELECT car_name , price, diff FROM(
  SELECT car_name,price,(@next_row_price - price) * -1 AS diff, 
  IF(@next_row_price IS NULL, @next_row_price := price, 0) ,
  IF(@next_row_price IS NOT NULL, @next_row_price := price, 0) 
FROM car 
) AS TEMP;

SQLFiddle

答案 2 :(得分:0)

试试这个: -

CREATE TABLE #TempTable (rownum INT, price int, car_name VARCHAR(256));
INSERT INTO #TempTable (rownum, price, car_name)
SELECT
 rownum = ROW_NUMBER() OVER (ORDER BY c.car_id),
 c.price,
 c.car_name
 FROM car c;
 SELECT
  NEX.car_name + '-' + TT.car_name,
  (nex.price - tt.price) AS Differences
  FROM #TempTable TT
LEFT JOIN #TempTable prev ON prev.rownum = TT.rownum - 1
LEFT JOIN #TempTable nex ON nex.rownum = TT.rownum + 1;