简体   繁体   中英

SQL query for getting next record value in previous row

i have this table for example:

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

and this SQL query:

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

in the table above (image table) i have only the minqty (minimum quantity) and i want to set the maxqty (maximum quantity) 1 less than minqty of the next record. for example at row 1: 4 (5-1) at row 2: 7 (8-1) and so on...

i want this result:

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

how i can do this with SQL or classic ASP or PHP; thanks in advance.

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

If the table is very large, performance of that may be poor. This should be faster:

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

In either case, make sure you have an index on qty .

UPDATE:

Maybe this is what you're looking for:

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"

Here's a query that works with the subset data you posted:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM