Select 来自 sql 服务器的最大日期 table 以 "mm-yyyy" 格式保存为 varchar 数据

Select max date from sql server table saved as varchar data in "mm-yyyy" format

在 table 中,日期数据保存为 mm-yyyy 格式,其数据类型为 varchar。

现在我想检索 MAX 日期。

日期保存格式如下,有几千条记录:

7-1986
10-2012
6-1989
5-1975
7-1974
7-1961
12-1987
10-1975
6-1959
10-2002
12-1991
11-1961
6-1966
12-1959
10-1956
12-1953
6-1999
2-1989 

我试过了:

SELECT MAX(CONVERT(DATETIME, '1-'+[Date], 105)) As MAXDate FROM tablename

但是是returns2015-12-01 00:00:00.000,不过应该是2015-01-01 00:00:00.000,因为MAX日期保存为1-2015.

你可以试试

SELECT Max(cast('1-'+Date as DateTime)) As MAXDate FROM tablename

可以使用STUFF函数添加-1:

SELECT MAX(CONVERT(DATETIME, STUFF([Date], CHARINDEX('-', [Date]), 0, '-1'), 121))

你可以试试:

SELECT MAX(CAST(RIGHT(Datestring, 4) + RIGHT('00' + SUBSTRING(DateString, 1, CHARINDEX('-', DateString, 1) - 1), 2) + '01' AS SMALLDATETIME)) FROM [YourTable]

样本:

CREATE TABLE #Dates(DateString  VARCHAR(10))
INSERT INTO #Dates VALUES
('7-1986'), ('10-2012'), ('6-1989'),
('5-1975'), ('7-1974'), ('7-1961'),
('12-1987'), ('10-1975'), ('6-1959'),
('10-2002'), ('12-1991'), ('11-1961'),
('6-1966'),  ('12-1959'), ('10-1956'),
('12-1953'),  ('6-1999'), ('2-1989');

;WITH CTE AS(
    SELECT
        DateString,
        [Month] = SUBSTRING(DateString, 1, CHARINDEX('-', DateString, 1) - 1),
        [Year] = RIGHT(Datestring, 4),
        [Date] = CAST(RIGHT(Datestring, 4) + RIGHT('00' + SUBSTRING(DateString, 1, CHARINDEX('-', DateString, 1) - 1), 2) + '01' AS SMALLDATETIME)  
    FROM #Dates
)
SELECT MAX([Date]) AS MaxDate FROM CTE

数据

DateString
----------
7-1986
10-2012
6-1989
5-1975
7-1974
7-1961
12-1987
10-1975
6-1959
10-2002
12-1991
11-1961
6-1966
12-1959
10-1956
12-1953
6-1999
2-1989

结果

MaxDate
-----------------------
2012-10-01 00:00:00