My problem stems from this:
VBA (Excel) vs SQL - Comparing values in two rows (loop)
I've modified the script a tad and it looks like this:
;WITH data AS
(
SELECT a.i, a.M, b.M as NextM,
CASE WHEN a.M = 65 AND b.M = 120 THEN 1 ELSE 0 END AS shouldIncreaseQ
FROM MyTable a
LEFT OUTER JOIN MyTable b
ON a.i + 1 = b.i
), test as
(
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
)
So now lets select * from test. I get something that looks like this.
M NextM Q
65 65 1
65 65 1
65 120 2
120 63 2
65 120 3
120 NULL 3
NOW.. all I want to is take the Q column (where Q pertains to the NextM) and put that in my original mytable.
So something like this:
i M Q
1 65 1
2 65 1
3 120 2
4 63 2
5 120 3
6 55 3
I hope that makes sense. I have been playing with select into, and even insert into all DAY (literally hours) with no luck. (using every type of join you can imagine)
Thank you in advance. (also can someone tell me how to make my tables look nicer.. do you use html to do it or what)?
UPDATE:
;WITH data AS
(
SELECT a.i, a.M, b.M as NextM,
CASE WHEN a.M = 65 AND b.M = 120 THEN 1 ELSE 0 END AS shouldIncreaseQ
FROM MyTable a
LEFT OUTER JOIN MyTable b
ON a.i + 1 = b.i
),
test as
(
SELECT data.i, data.M, data.NextM,
(SELECT COUNT(*) + 1 FROM data AS ref
WHERE ref.shouldIncreaseQ = 1 AND ref.i <= data.i) as Q FROM data
),
final as
(
select a.i, a.M as zw_step, b.Q as prodid
from test a
left outer join test b
on a.i - 1 = b.i
)
SELECT final.i, final.zw_step, final.prodid
FROM final
Now.. the select statement is how I like it. EXCEPT the darn thing will not work with a insert into command.. (you might have to fool around with final). I'm now afraid of CTE, I will probably never use them again this.
Thanks for your help everyone.
Okay, I'm not quite sure if I understand correctly what you are looking for. But you might want to replace
SELECT final.i, final.zw_step, final.prodid
FROM final;
with
UPDATE MT
SET MT.Q = F.prodid
FROM MyTable AS MT
INNER JOIN final AS F ON MT.i = F.i AND MT.M = F.zw_step;
This will replace the values in column Q
in MyTable
with the values in column prodid
in final
. Is this what you're trying to do? (Based on "NOW.. all I want to is take the Q column (where Q pertains to the NextM) and put that in my original mytable.")