逐列更新行

时间:2013-01-15 13:59:57

标签: sql sql-server

我有一个包含4列的表格:

| PromoId | Amount| PromoType  |Description|
--------------------------------------------------
|   101   |   11  |      a     |     free|       
|   101   |   12  |      a     |     20% |       
|   103   |   17  |      c     |     45% |       
|   104   |   14  |      c     |     50% |   

我必须将PromoId和PromoType的相同值的描述组合在一起。

对于上述表格,我的输出应该是:

| PromoId | Amount| PromoType  |Description|
--------------------------------------------------
|   101   |   11  |      a     |     free 20% |       
|   101   |   12  |      a     |     free 20% |       
|   103   |   17  |      c     |     45%      |       
|   104   |   14  |      c     |     50%      |   

我正在使用SQL Server。 提前谢谢。

3 个答案:

答案 0 :(得分:1)

WITH ConcatValue
AS
(
  SELECT
       PromoId,
       STUFF(
           (SELECT ' ' + Description
            FROM TableName
            WHERE PromoId = a.PromoId
            FOR XML PATH (''))
            , 1, 1, '')  AS Title
  FROM TableName AS a
  GROUP BY PromoId
)
SELECT   a.PromoId, a.Amount, a.PromoType,
         b.Title
FROM     tableName a
         INNER JOIN ConcatValue b
            ON a.PromoId = b.PromoId

答案 1 :(得分:1)

这是我的解决方案

select d.PromoId, d.Amount, d.PromoType, Left(x.Description,Len(x.Description)-1)
from demo d
join (
    select distinct x1.PromoId, 
    (select x2.Description + ',' from demo x2 where x2.PromoId = x1.PromoId For XML PATH ('')) Description
    from demo x1) x on d.PromoId = x.PromoId

Acknowledgements

答案 2 :(得分:0)

您需要字符串连接,这在SQL Server中有点麻烦。这是一种方式:

select t.*,
       (select t2.description+' '
        from t t2
        where t2.promoID = t.promoID and t2.promoType = t.promotType
        order by t2.amount
        for xml path ('')
       ) as CombinedDescription
from t

这会在末尾留下一个空间,你可以剪掉它。