简体   繁体   English

如何在表格中找到最近的12个日期?

[英]How do I find the 12th most recent date in a table?

I have a table containing sales information by customer account and posting month. 我有一个表格,其中包含按客户帐户和发布月份列出的销售信息。 The posting month is a text field formatted as YYMM. 过帐月份是一个格式为YYMM的文本字段。 I can easily write a query to return the distinct posting months in descending order, but how do I pick the 12th row from that? 我可以轻松地编写查询以降序返回不同的发布月份,但是如何从中选择第12行呢? I want to find the posting month 12 months prior to the most recent recorded, ideally as a scalar subquery so that it can be used as a selection criterion. 我想查找最近记录的12个月之前的发布月份,理想情况下是标量子查询,以便可以用作选择标准。 At the moment this parameter is supplied by a UDF but I suspect performance would be better from a subquery. 目前,此参数由UDF提供,但是我怀疑从子查询中可以获得更好的性能。

You can get the 12th by doing: 您可以通过执行以下操作获得第十二名:

select distinct month
from t
order by month desc
offset 11
fetch first 1 row only;

This is ANSI SQL, but it will not work in all databases. 这是ANSI SQL,但不适用于所有数据库。 However, most databases support similar functionality. 但是,大多数数据库都支持类似的功能。

You could use a "window function" to identify the 12th row, as follows... 您可以使用“窗口函数”来标识第十二行,如下所示...

    ;WITH cteExampleData
        (
        PostingMonth,
        Data
        )
        AS
        (
        SELECT '1611', 'Test1'
        UNION ALL SELECT '1612', 'Test2'
        UNION ALL SELECT '1701', 'Test3'
        UNION ALL SELECT '1601', 'Test4'
        UNION ALL SELECT '1602', 'Test5'
        UNION ALL SELECT '1604', 'Test6'
        UNION ALL SELECT '1605', 'Test7'
        UNION ALL SELECT '1501', 'Test8'
        UNION ALL SELECT '1502', 'Test9'
        UNION ALL SELECT '1503', 'Test10'
        UNION ALL SELECT '1401', 'Test11'
        UNION ALL SELECT '1403', 'Test12'
        UNION ALL SELECT '1404', 'Test13'
        UNION ALL SELECT '1405', 'Test14'
        UNION ALL SELECT '1406', 'Test15'
        )
        SELECT *
            INTO #ExampleData
            FROM cteExampleData;

    ;WITH cteFind12thRow
        AS
        (
        SELECT RowNumber = ROW_NUMBER() OVER (ORDER BY PostingMonth),
            *
            FROM #ExampleData
        )
        SELECT * FROM cteFind12thRow
            WHERE RowNumber = 12

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM