用于获取上一行中下一个记录值的SQL查询

时间:2013-12-20 12:42:01

标签: php mysql sql asp-classic

我有这个表例如:

| prid  |  qty  | price |
| ----- |   1   |   20  |
| ----- |   7   |   18  |
| ----- |   12  |   15  |
| ----- |   20  |   12  |

和这个SQL查询:

prcrSql = "SELECT scaleqty, fld01, dim2, dim1, prcrule, finaldate FROM prcrdata WHERE finaldate>=getDate()-1 AND (dim1=30 OR dim1=40) ORDER BY dim2"
prcrRS.Open prcrSql

WHILE NOT prcrRS.EOF

insPRCR = "INSERT INTO prcr (mtrl,ofprice,minqty,maxqty,client,prcrule,fdate) VALUES ('"&prcrRS("dim2")&"','"&prcrRS("fld01")&"','"&prcrRS("minqty")&"','"&?????&"','"&prcrRS("dim1")&"','"&prcrRS("prcrule")&"','"&prcr("prdate")&"')"
myCon.Execute insPRCR

prcrRS.MoveNext
WEND

在上表(图像表)中我只有minqty(最小数量),我想设置maxqty(最大数量)1小于下一条记录的minqty。 例如在第1:4行(5-1) 在第2:7行(8-1) 等等...

我想要这个结果:

| prid  |  minqty  | maxqty | price |
| ----- |   1      |   6    |   20  |
| ----- |   7      |   11   |   18  |
| ----- |   12     |   19   |   15  |
| ----- |   20     |   -    |   12  |

我如何使用SQL或经典ASP或PHP来做到这一点; 提前谢谢。

1 个答案:

答案 0 :(得分:1)

SELECT t1.prid, t1.qty AS minqty, MIN(t2.qty)-1 AS maxqty, t1.price
FROM prcr t1
LEFT JOIN prcr t2 ON t2.qty > t1.qty
GROUP BY t1.qty

DEMO

如果表格非常大,那么表现可能会很差。这应该更快:

SELECT prid, qty AS minqty, @maxqty AS maxqty, price, @maxqty := qty-1
FROM prcr
CROSS JOIN (select @maxqty := null) var
ORDER BY minqty DESC

DEMO

在任何一种情况下,请确保您在qty上有索引。

更新:

也许这就是你要找的东西:

prcrSql = "SELECT p1.scaleqty AS minqty, MIN(p2.scaleqty)-1 AS maxqty, p1.fld01, p1.dim2, p1.dim1, p1.prcrule, p1.finaldate 
           FROM prcrdata p1
           LEFT JOIN prcrdata p2 ON p1.fld01 = p2.fld01 AND p2.scaleqty > p1.scaleqty AND p2.finaldate>=getDate()-1 AND (p2.dim1=30 OR p2.dim1=40)
           WHERE p1.finaldate>=getDate()-1 AND (p1.dim1=30 OR p1.dim1=40)
           GROUP BY p1.scaleqty, p1.fld01, p1.dim2, p1.dim1, p1.prcrule, p1.finaldate
           ORDER BY dim2"

这是一个与你发布的子集数据一起使用的查询:

SELECT p1.prid, p1.scaleqty AS minqty, MIN(p2.scaleqty)-1 AS maxqty, p1.price
FROM prcrdata p1
LEFT JOIN prcrdata p2 ON p2.scaleqty > p1.scaleqty AND p1.prid = p2.prid
GROUP BY p1.scaleqty, p1.prid, p1.price
ORDER BY p1.prid, p1.scaleqty

DEMO