SQL Extract & Convert string to a number then use it for calculation to generate a third column

22 Views Asked by At

I have:

col1(varchar), col2(float)
25-PACK      , 4

want to have:

col1 , col2, col3
25   , 4   , 100

This is what I have:

CAST(SUBSTRING(col1, CHARINDEX('-P',col1)-2 ,2) AS FLOAT) AS NewCol1, Col2, Col2*NewCol1 AS Col3

The issue here is NewCol1 is an invalid name. How do I resolve this issue? TIA.

1

There are 1 best solutions below

1
BachPhi On

I got it:

CAST(SUBSTRING(col1, CHARINDEX('-P',col1)-2 ,2) AS FLOAT) AS NewCol1, Col2, Col2*CAST(SUBSTRING(col1, CHARINDEX('-P',col1)-2 ,2) AS FLOAT) AS Col3