I have the below table where I need to replace the string in the column'Formula' with the matching input 'VALUE' column based on the group 'Yearmonth'.
IDNUM formula INPUTNAME VALUE YEARMONTH
1 imports(398)+imports(399) imports(398) 17.000 2003:1
2 imports(398)+imports(399) imports(398) 56.000 2003:2
3 imports(398)+imports(399) imports(399) 15.000 2003:1
4 imports(398)+imports(399) imports(399) 126.000 2003:2
</pre>
For eg :From the above table i need the output as
Idnum Formula Yearmonth
1. 17.00 +15.00 2003:1
2. 56.00 +126.00 2003:2
I tried with the below different query but coludnt achieve it. How can this be done ?
Type1 :
SELECT
REPLACE(FORMULA, INPUTName, AttributeValue) AS realvalues,
yearmonth
FROM table1
GROUP BY yearmonth
TYPE 2:
USING XML PATH... In this case it got worked but I need to replace only the strings with the values and not to stuff the strings based on mathematcal operation.(Because the formula might be of any type).
SELECT
IDNUM = MIN(IDNUM),
FORMULA =
(SELECT STUFF(
(SELECT ' +' + CONVERT(VARCHAR(10), Value)
FROM Table1
WHERE YEARMONTH = t1.YEARMONTH
FOR XML PATH(''))
,1, 2, '')),
YEARMONTH
FROM Table1 t1
GROUP BY YEARMONTH
Type3:
I'm getting only the null value as output.
;with t as (
select t.*,
row_number() over (partition by yearmonth order by idnum) as seqnum,
count(*) over (partition by yearmonth) as cnt
from table t
),
cte as (
select t.seqnum, t.yearmonth, t.cnt,
replace(formula, inputname, value) as formula
from t
where seqnum = 1
union all
select cte.seqnum, cte.yearmonth, cte.cnt,
replace(formula, t.inputername, t.value)
from cte join
t
on cte.yearmonth = t.yearmonth and cte.seqnum = t.seqnum + 1
)
select row_number() over (order by (select null)) as id,
formula
from cte
where seqnum = cnt