我有2列日期和年份。在该日期之下,一年中每个月都有行。为了只显示年份列的不同值,我用空值替换了重复项,但是当我在报表中调用该列时,它只在每年之间放置了空白行。此表严格用于创建可用于过滤报表的参数列表。
现在我的表看起来像这样:
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 :(得分: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