MySQL查询不同列中上一行和下一行值之间的差异

时间:2014-04-29 13:35:17

标签: mysql sql-server

This is DistributorTransaction Table where
FullJarsOut = QuantityDelivered + Spoiled + FullJarsReturn

ID     FullJarsOut      QuantityDelivered      Spoiled         FullJarsReturn
P1     100              70                     10              20
P2     200              180                    5               15
P3     300              260                    13              27

where I want output from above table as

FullJarsOut        FullJarsReturn         Delivered (FullJarsOut – FullJarsReturn)
100                       0                      100
200                       20                     180
300                       15                     285
I want difference of 
200 from FullJarsOut column with 20 in FullJarsReturn(previous colums) as 200 - 20
300 from FullJarsOut column with 15 in FullJarsReturn(previous colums) as 300 - 15
from DistributorTransaction Table

2 个答案:

答案 0 :(得分:0)

SQL Server版本

WITH ordered_xactions as
  (
    select id, FullJarsOut, FullJarsReturn, Rank() OVER (ORDER BY ID) rank_id
     FROM DistributorTransaction
  )
SELECT 
  ox1.FullJarsOut FullJarsOut
  ,COALESCE(ox2.FullJarsReturn, 0) FullJarsReturn
  ,(ox1.FullJarsOut - COALESCE(ox2.FullJarsReturn, 0)) Delivered
FROM ordered_xactions ox1
LEFT JOIN ordered_xactions ox2
ON ox2.rank_id = ox1.rank_id - 1;

首先,根据ID对数据进行排名。然后,从当前行的FullJarsOut中减去排名较低的行的FullJarsReturn值。

SQL Fiddle

MySQL版

SELECT 
  d1.FullJarsOut
  ,d2.FullJarsReturn
  ,d1.FullJarsOut - d2.FullJarsReturn Delivered
FROM DistributorTransaction d1
INNER JOIN
(SELECT dt1.ID, COALESCE(MAX(dt2.ID), dt1.ID) max_id
 FROM DistributorTransaction dt1
 LEFT JOIN DistributorTransaction dt2
 ON dt2.ID < dt1.ID
 GROUP by dt1.ID
) max_ids
ON d1.ID = max_ids.ID
INNER JOIN DistributorTransaction d2
ON d2.ID = max_ids.max_id;

SQL Fiddle

答案 1 :(得分:0)

@ Joseph-b感谢您回答这个问题。我使用了mysql版本,我在查询中做了一些更改。

SELECT d1.FullJarsOut ,COALESCE(d2.FullJarsReturn,0) FullJarsReturn ,COALESCE(d1.FullJarsOut - d2.FullJarsReturn,0) Delivered FROM DistributorTransaction d1 LEFT OUTER JOIN (SELECT dt1.ID, COALESCE(MAX(dt2.ID), 0) max_id FROM DistributorTransaction dt1 LEFT JOIN DistributorTransaction dt2 ON dt2.ID < dt1.ID GROUP BY dt1.ID ) max_ids ON d1.ID = max_ids.ID LEFT OUTER JOIN DistributorTransaction d2 ON d2.ID = max_ids.max_id