簡體   English   中英

SQL Server 2008將兩行合並為一

[英]SQL Server 2008 Combine two rows into one

到目前為止,我已經編寫了非常簡單的查詢,因此現在我正在尋找一種幫助編寫SQL語句,以便它將表中的兩個獨立的期末行合並為一行。 這些行基本上可以通過其PId,區域,市場,代碼,源進行匹配。 例如-

如果第一行是:

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
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

如果我正確理解你的問題,你要pivot多行成多列。

假設它總是你要結合2行,並使用period_end場順序從第二個第一,那么這樣的事情應該工作使用maxcase ,以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來獲得結果。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM