是否有任何独特的 SQL 函数可以从时间戳中仅检索年份和月份,并根据该结果我需要找出最早的

is there any unique SQL function to retrieve only year and month from the timestamp and based on that result i need to find out the earliest made

我试过下面提到的代码,但它给出了不同的答案 使用的代码

 $SELECT  MIN(DATENAME(MM,orders.occurred_at)) AS 'Month',
            MIN(DATENAME(YY,orders.occurred_at)) AS 'Year'
    FROM orders

TABLE

id  account_id  occurred_at
1   1001    2015-10-06 17:31:14.000
2   1001    2015-11-05 03:34:33.000
3   1001    2015-12-04 04:21:55.000
4   1001    2016-01-02 01:18:24.000
5   1001    2016-02-01 19:27:27.000
6   1001    2016-03-02 15:29:32.000
7   1001    2016-04-01 11:20:18.000
8   1001    2016-05-01 15:55:51.000
9   1001    2016-05-31 21:22:48.000
10  1001    2016-06-30 12:32:05.000
11  1001    2016-07-30 03:26:30.000
12  1001    2016-08-28 07:13:39.000
13  1001    2016-09-26 23:28:25.000
14  1001    2016-10-26 20:31:30.000
15  1001    2016-11-25 23:21:32.000
16  1001    2016-12-24 05:53:13.000
17  1011    2016-12-21 10:59:34.000
18  1021    2015-10-12 02:21:56.000
19  1021    2015-11-11 07:37:01.000
20  1021    2015-12-11 16:53:18.000

试试,

    SELECT  MONTH(occurred_at) AS Month,
            YEAR(occurred_at) AS Year
    FROM orders

   SELECT  FORMAT(occurred_at, 'MMMM') AS Month,
            FORMAT(occurred_at, 'yyyy') AS Year
    FROM orders

SELECT  
   FORMAT(occurred_at, 'y') AS 'Month and Year',
FROM orders

我不明白您是想查看所有结果并只是对它们进行排序以便最早的实例出现在列表中的第一位,还是您只想要最早的记录本身。

按时间戳对列表进行排序并根据时间戳显示 Month()Year() 非常简单:

SELECT
   ID
  ,Account_ID
  ,Occurred_At
  ,MONTH(Occurred_At) AS Occurred_Month
  ,YEAR(Occurred_At) AS Occurred_Year
FROM Orders
ORDER BY Occurred_At ASC -- This puts the oldest record at the top of the list
;

如果你只想检索最旧的记录,那么你可以这样做:

SELECT TOP 1 -- This returns only the topmost record
   ID
  ,Account_ID
  ,Occurred_At
  ,MONTH(Occurred_At) AS Occurred_Month
  ,YEAR(Occurred_At) AS Occurred_Year
FROM Orders
ORDER BY Occurred_At ASC  -- This puts the oldest record at the top of the list
;

据推测,您不需要从 Occurred_At 中提取月份和年份来了解哪个顺序是第一个……时间戳为您提供了该信息。但是,如果出于某种原因,您想按月份和年份而不是完整时间戳进行排序:

SELECT TOP 1
   ID
  ,Account_ID
--,Occurred_At -- If you don't need this line, you can remove it...
  ,MONTH(Occurred_At) AS Occurred_Month
  ,YEAR(Occurred_At) AS Occurred_Year
FROM Orders
ORDER BY Occurred_Year ASC, Occurred_Month ASC
;