美好的一天
我返回了以下结果集:
financeYearEnd FromDate ToDate ClientPortfolioCode
2013-12-31 00:00:00.000 2014-01-01 2014-01-31 C1
2013-12-31 00:00:00.000 2014-01-01 2014-01-31 C2
2012-12-31 00:00:00.000 2013-12-01 2013-12-31 C1
2012-12-31 00:00:00.000 2013-12-01 2013-12-31 C2
我需要做的是:
我需要比较所有C1 Fields的financeYearEnd(总是只有两个),看看它们是否彼此不同
2013-12-31 00:00:00.000 2014-01-01 2014-01-31 C1
2012-12-31 00:00:00.000 2013-12-01 2013-12-31 C1
如图所示,financeYearEnd确实不同,所以我需要将该结果作为一行存储在临时表中。
这需要针对所有不同的ClientPortfolioCodes(总是以两个为一组出现)进行。
如何实现这一目标?
我试过select distinct ..
- 没有工作。它返回了我的所有行
编辑 -
WITH cteCompareTopTwoYears
AS (
SELECT TOP (
SELECT COUNT(*) * 2
FROM #ClientPortFolios
) FinancialYearEnd AS financeYearEnd
,FromDate
,ToDate
,CA.ClientPortfolioCode
FROM rpt.F3_fn_ClientPortfolios_CapitalAccount_IncludingYTD CA
WHERE (
(
CA.FromDate = (DATEADD(m, - 1, @FromDate))
AND CA.ToDate = (DATEADD(m, - 1, @ToDate))
)
OR (
CA.FromDate = @FromDate
AND CA.ToDate = @ToDate
)
)
AND (
CA.ClientPortFolioCode IN (
SELECT ClientPortfolioCode
FROM #ClientPortfolios
)
)
ORDER BY FromDate DESC
)
SELECT *
FROM cteCompareTopTwoYears c
答案 0 :(得分:1)
也许在ROW_NUMBER
的帮助下,例如:
WITH CTE AS
(
SELECT financeYearEnd, FromDate, ToDate, ClientPortfolioCode,
rn = row_Number () OVER (Partition By ClientPortfolioCode
Order By financeYearEnd ASC)
FROM dbo.TableName
)
SELECT financeYearEnd, FromDate, ToDate, ClientPortfolioCode
FROM CTE
WHERE rn > 1