2013-12-13 55 views
1

我有2列日期和年份。在該日期下,每年的每月都有行。爲了僅顯示年份列的不同值,我用空值替換了重複項,但是當我在報告中調用該列時,它僅在每年之間放置了空白行。此表格嚴格用於創建可用於過濾報告的參數列表。結合不同數量的行的2列,並沒有什麼共同的SQL

現在我的表看起來是這樣的:

Date  Year 
----------------- 
1/2013  2013 
2/2013  2013 
3/2013  2013 
. 
. 
. 
12/2013  2013 
1/2014  2014 
2/2014  2014 

以下是我想表的樣子。

Date  Year 
----------------- 
1/2013  2013 
2/2013  2014 
3/2013  2015 
.    . 
.    . 
.    . 
12/2013  . 
1/2014  . 
2/2014  . 

這裏是我使用的查詢:

  SELECT rmp.EcoDate as Date, 
      year(rmp.EcoDate) as Year, 

      FROM  PhdRpt.ReportCaseList_542 AS rcl INNER JOIN 
         CaseCases AS cc ON rcl.CaseCaseId = cc.CaseCaseId INNER JOIN 
         PhdRpt.RptMonthlyProduction_542 AS rmp ON rcl.ReportRunCaseId = rmp.ReportRunCaseId 
      GROUP BY rmp.EcoDate 

是實現這個創建2個臨時表和建立一個共同視野使得一行,並在該行的連接或者是最好的方法有更乾淨的方法嗎?在年底的專欄結尾,我預計只剩下空位來填寫剩下的行。

非常感謝您的幫助。

+0

基本上,你想每個日期順序編號?爲什麼從2013年開始? –

+1

請說清楚你想做什麼...... –

+0

它不一定在2013年開始。它始於無論查詢的第一個日期是什麼年份。 –

回答

1

我可以通過在自己的臨時表中分組年份和日期,然後使用row_number創建一個公共列,然後使用第一個表到第二個表進行完整的外部聯接來解決此問題。這裏是查詢:

SELECT  CAST(MONTH(rmp.EcoDate) AS Varchar(2)) + '/' + CAST(YEAR(rmp.EcoDate) AS varchar(4)) AS Date, 
      rmp.EcoDate as EcoDate, 
      row_number() over (order by rmp.ecodate) as seqnum 
into #a 
FROM   PhdRpt.ReportCaseList_542 AS rcl INNER JOIN 
         CaseCases AS cc ON rcl.CaseCaseId = cc.CaseCaseId INNER JOIN 
         PhdRpt.RptMonthlyProduction_542 AS rmp ON rcl.ReportRunCaseId = rmp.ReportRunCaseId 
GROUP BY rmp.EcoDate 

SELECT  year(rmp.EcoDate) as Year, 
      CONVERT (datetime,convert(char(8),YEAR(rmp.EcoDate))) as EcoYear, 
      row_number() over (order by year(rmp.ecodate)) as seqnum 
into #b 
FROM   PhdRpt.ReportCaseList_542 AS rcl INNER JOIN 
      CaseCases AS cc ON rcl.CaseCaseId = cc.CaseCaseId INNER JOIN 
      PhdRpt.RptMonthlyProduction_542 AS rmp ON rcl.ReportRunCaseId = rmp.ReportRunCaseId 
GROUP BY year(rmp.EcoDate) 

Select * 
From #a a 
Full Outer Join #b b on a.seqnum = b.seqnum 

drop table #a, #b 
相關問題