SQL Server 2008将两行合并为一行

时间:2014-08-26 23:20:09

标签: sql sql-server-2008

到目前为止,我已经编写了相当简单的查询,因此我现在正在寻找帮助来编写SQL语句,以便将表中的两个单独的句点结束行组合成一行。这些行基本上可以通过它们的PId,Region,Market,Code,Source匹配。例如 -

如果第一行是:

Id   Region Market  CODE    Source  Period_End  Amt     Pct
100 CAN     CABLE   V1      SA      20120930    100.00  0.2

和第二行是:

Id  Region  Market  CODE    Source  Period_End  Amt     Pct 
100 CAN     CABLE   V1      SA      20121231    200.00  0.5

然后SQL应该返回这个结果:

Id  Region  Market  CODE    Source  Period_End_1    Amt_1   Pct_1   Period_End_2    Amt_2   Pct_2

100 CAN     CABLE   V1      SA      20120930        100.00  0.2     20121231        200.00  0.5

非常感谢您的帮助。

安娜。


感谢您的回复。这就是我的开始,但我不确定我是否正确的方向。我还注意到,因为我会根据Period End向行添加越来越多的信息,所以下面的查询会因冗余" case condition"而过长。在每个选择中。

select 
    A.id , A.region, A.market, A.code, A.source ,  
    case when period_end = @day_id1 then period_end else '' end as Period_End_1,
    case when period_end = @day_id2 then period_end else '' end as Period_End_2, 
    case when period_end = @day_id1 then Amt else 0.0 end as Amt_1,
    case when period_end = @day_id2 then Amt else 0.0 end as Amt_2, 
    case when period_end = @day_id1 then Pct else 0.0 end as Pct_1,
    case when period_end = @day_id2 then pct else 0.0 end as Pct_2, 
from 
    products A with (nolock)
where 
    A.product_id in (select product_id from #products) -- temp table holding multiple Ids

2 个答案:

答案 0 :(得分:0)

SELECT t1.Id  
      ,t1.Region  
      ,t1.Market  
      ,t1.CODE    
      ,t1.Source
      ,t1.Period_End  AS Period_End_1 
      ,t1.Amt         AS Amt_1
      ,t1.Pct         AS Pct_1
      ,t2.Period_End  AS Period_End_2 
      ,t2.Amt         AS Amt_2
      ,t2.Pct         AS Pct_2
FROM Table_Name t1 
INNER JOIN TABLE_Name t2  ON t1.ID = t2.ID
WHERE t1.ID = 100 AND t1.Period_End <> t2.Period_End

答案 1 :(得分:0)

如果我正确理解您的问题,那么您尝试将pivot多行划分为多个列。

假设您总是尝试合并2行,使用period_end字段对第一行进行排序,那么使用maxcase的{​​{1}}就可以了pivot您的结果:

WITH CTE AS (
    SELECT *, 
           Row_Number() Over (Partition By Id, Region, Market, Code, Source 
                              Order By Period_End) rn
    FROM YourTable
)
SELECT Id, 
    Region, 
    Market, 
    Code,   
    Source,
    max(case when rn = 1 then Period_End end) Period_End_1,
    max(case when rn = 1 then Amt end) Amt_1,
    max(case when rn = 1 then Pct end) Pct_1,
    max(case when rn = 2 then Period_End end) Period_End_2,
    max(case when rn = 2 then Amt end) Amt_2,
    max(case when rn = 2 then Pct end) Pct_2
FROM CTE
GROUP BY Id, Region, Market, Code, Source

如果您有更多潜在的period_end日期,那么您可能需要使用动态SQL来实现结果。