2016-01-04 48 views
0

我有下面的表格,我需要根據組「Yearmonth」將匹配輸入「VALUE」列替換爲'Formula'列中的字符串。如何使用sql中的group by子句替換字符串?

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 

對於前:從上面的表,我需要的輸出作爲

Idnum Formula  Yearmonth 
1. 17.00 +15.00 2003:1 
2. 56.00 +126.00 2003:2 

我用下面的查詢嘗試,但未能實現。如何才能做到這一點 ?

SELECT 
    REPLACE(FORMULA, INPUTName, AttributeValue) AS realvalues, 
    yearmonth 
FROM table1 
GROUP BY yearmonth 

回答

1

使用FOR XML PATH進行連結:

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 
+0

這工作正常...非常感謝....我有一個問題,這將適用於任何類型的字符串在表中或只爲這種類型? –

+0

看來這個querey適用於在公式中有'+'的字符串....有沒有什麼辦法可以在不考慮數學符號的情況下只替換字符串名? –

1

不幸的是,這種類型的更換需要遞歸:

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 t.seqnum = cte.seqnum + 1 
    ) 
select row_number() over (order by (select null)) as id, 
     formula 
from cte 
where seqnum = cnt; 
+0

感謝您的建議...但我相信querey需要一些修改..我有點努力得到輸出..... –

+0

嗨戈登....我試過代碼執行,但我越來越onlu null值...你能幫我解決這個問題 –

+0

@JamesRodix。 。 。你可以設置一個SQL小提琴嗎? –

0
SELECT t1.yearmonth, 
    formula=REPLACE((SELECT value AS [data()] 
     FROM table t2 
     WHERE t2.YEARMONTH= t1.YEARMONTH 
     ORDER BY value 
     FOR XML PATH('') 
     ), ' ', '+') 
    FROM table t1 
    GROUP BY YEARMONTH ; 

如果u需要列IDNUM試試這個

declare @t table (idnum int identity(1,1),formula varchar(100),Yearmonth date) 
insert into @t 
    SELECT t1.yearmonth, 
    formula=REPLACE((SELECT value AS [data()] 
     FROM table t2 
     WHERE t2.YEARMONTH= t1.YEARMONTH 
     ORDER BY value 
     FOR XML PATH('') 
     ), ' ', '+') 
    FROM table t1 
    GROUP BY YEARMONTH ; 
+0

嗨...感謝您的建議......它與Felix Pamittan的建議完全相同......請對我提出的意見給予他的建議..會這樣嗎? –