0

我有一个有 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。提前致谢。

4

3 回答 3

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

致谢

于 2013-01-15T14:24:11.400 回答
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
于 2013-01-15T14:20:50.333 回答
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

这会在最后留下一个空间,您可以将其修剪掉。

于 2013-01-15T14:12:40.047 回答