0

我有一个包含 2 列的表,应该只包含一个值,但有些条目包含 2 或 3 个值。对于这些问题行,所有其他列都是相同的。

Table A - Currently 
Deal ID | PA ID | other columns 
1         2       xxxxx
1,2       2       xxxxx
3         1,5     xxxxx

我想要的是

Deal ID | PA ID | other columns 
1         2       xxxxx
1         2       xxxxx
2         2       xxxxx
3         1       xxxxx
3         5       xxxxx 

不知道该怎么做?认为我需要UNPIVOT然后删除 ,。

4

2 回答 2

0

解决方案是:

DECLARE @t TABLE ( 
  DealID VARCHAR(10), 
  PAID   VARCHAR(200), 
  [DESC] VARCHAR(100)) 

INSERT @t 
SELECT '1', 
       '2', 
       'xxxx' 
UNION ALL 
SELECT '1,2', 
       '2', 
       'xxxx' 
UNION ALL 
SELECT '3', 
       '1,5', 
       'xxxx' 

SELECT LEFT(b, Charindex(',', b + ',') - 1) AS DealID, 
       LEFT(d, Charindex(',', d + ',') - 1) AS PAID, 
       [Desc] 
FROM   (SELECT Substring(DealID, DE.number, 200) AS b, 
               Substring(PAID, PA.number, 200)   AS d, 
               [Desc] 
        FROM   @t DealID 
               LEFT JOIN (SELECT DISTINCT number 
                          FROM   master.dbo.spt_values 
                          WHERE  number BETWEEN 1 AND 200) PA 
                 ON Substring(',' + PAID, PA.number, 1) = ',' 
               LEFT JOIN (SELECT DISTINCT number 
                          FROM   master.dbo.spt_values S 
                          WHERE  number BETWEEN 1 AND 200) DE 
                 ON Substring(',' + DealID, DE.number, 1) = ',') t 
于 2012-05-25T10:13:36.463 回答
0

这是一种解决方案。这是蛮力并使用 union all 来获取多个副本:

with incols as (
     select (case when charindex(Dealid, ',') > 0
                  then left(DealId, charindex(Dealid, ',') - 1)
                  else DealId
             end) as DealId1,
            (case when charindex(Dealid, ',') > 0
                  then substring(DealId, charindex(DealId, ',') + 1, 100)
             end) as DealId2,
            (case when charindex(PAId, ',') > 0
                  then left(PAId, charindex(PAId, ',') - 1)
                  else PAId
             end) as PAId1,
            (case when charindex(PAId, ',') > 0
                  then substring(PAId, charindex(PAId, ',') + 1, 100)
             end) as PAId2,
            t.*
     from t
    ),
    deals as (
     select (case when whichdeal = 1 then deal1 else deal2 end) as newdeal, t.*
     from ((select *, 1 as whichdeal
            from t
           ) union all
           (select *, 2 as whichdeal
            from t
            where deal2 is not null
           ))  t
    )
select newdeal as dealid, t.*
from deals

包括 PA 需要添加另一个 CTE,然后在 dealid 和 PA id 上加入交易和 PA 以获得所有可能的组合。当两行中都有重复项时,您没有准确指定要发生的事情,所以我只是猜测您会想要所有组合。

于 2012-05-24T15:45:18.600 回答