VBA (Excel) vs SQL - Comparing values in two rows

2019-05-18 08:09发布

问题:

Is this possible in SQL? It seems like a simple concept. (I'm using SQL Server 2005)

Loop through all the rows in my SQL table compare the values in column m if one row =65 and the next equals 120 increase j, and print that value in another column (column q)

Sub InsertProductionCycle() 

Dim LR As Long 
Dim j As Integer 

j = 1 
LR = Range("G" & Rows.Count).End(xlUp).Row 

    For i = 1 To LR Step 1 

        Cells(i, "Q").Value = j 

        If Cells(i, "M").Value = 65 And Cells(i + 1, "M").Value = 190 Then 
            j = j + 1 
        End If 
    Next i 

End Sub 

Any thoughts from the SQL experts? Can I do this in SQL? My thoughts about this is: Perhaps the loop is a bit of a stretch, (I can run that in a sql job), but can you compare the rows and insert the j loop value in another column. Thats where I'm stuck.

回答1:

This was a fun one! There may be a more efficient way to do this, but you can do it in a single set-based statement without the need for loops or cursors.

Assuming a table that models your data that looks something like this (where i is basically your row number):

CREATE TABLE MyTable (i int, M int)

I used a self join to match i rows with i+1 rows and used a COUNT to figure out the Q column.

;WITH data AS (
    SELECT a.i, a.M, b.M as NextM
        , CASE WHEN a.M = 65 AND b.M = 190 THEN 1 ELSE 0 END AS shouldIncreaseQ
    FROM MyTable a
       LEFT OUTER JOIN MyTable b
          ON a.i + 1 = b.i
)
SELECT data.M, data.NextM
   , (SELECT COUNT(*) + 1 FROM data AS ref 
      WHERE ref.shouldIncreaseQ = 1 AND ref.i <= data.i) as Q
FROM data

If need be, you could use SELECT INTO to get the data into another table for future use.