在sql中结合最小和最小最小值

时间:2016-09-08 09:45:09

标签: sql-server

我有以下查询来计算第一个即将到来的营业日期,如下所示:

INDEX

现在我想要一个包含第二个即将到来的营业日期的专栏。我希望在同一个SQL查询中。如何选择最小和最小?

1 个答案:

答案 0 :(得分:0)

Use rownumber with CTE..

    ;with cte
    as
    (SELECT LAST_CLOSING_BALANCE_DATES.ACCT_NBR, row_number() over ( order by  BUSINESS_DATES.DATE_VALUE ) AS FIRST_BUSINESS_DAY
    FROM BUSINESS_DATES JOIN SD_CALENDAR ON BUSINESS_DATES.CODE = SD_CALENDAR.CODE
        JOIN  AS_AS_RECEPTION_CONF ON AS_AS_RECEPTION_CONF.CALENDAR_ID = SD_CALENDAR.ID
        JOIN SD_ACCT_GRP ON AS_AS_RECEPTION_CONF.ACCT_GRP_ID = SD_ACCT_GRP.ID
        JOIN SD_ACCT_GRP_MEMBER ON SD_ACCT_GRP.ID = SD_ACCT_GRP_MEMBER.GRP_ID
        JOIN SD_ACCT ON SD_ACCT.ID = SD_ACCT_GRP_MEMBER.ACCT_ID
        JOIN LAST_CLOSING_BALANCE_DATES ON SD_ACCT.ACCT_NBR = LAST_CLOSING_BALANCE_DATES.ACCT_NBR
    WHERE BUSINESS_DATES.DATE_VALUE > LAST_CLOSING_BALANCE_DATES.BAL_DATE
    GROUP BY LAST_CLOSING_BALANCE_DATES.ACCT_NBR
    )
    select ACCT_NBR,
min(DATE_VALUE) as firstbusiness,
max(DATE_VALUE)as secondbusiness from cte where rn<=2
group by ACCT_NBR