如何在sql中使用group by子句替换字符串?

时间:2016-01-04 03:08:57

标签: sql sql-server sql-server-2008

我有下表,我需要根据'Yearmonth'组的匹配输入'VALUE'列替换'Formula'列中的字符串。

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

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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;

答案 2 :(得分: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 ;

如果你需要列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 ;