我有一张年,月,日的表格如下。
Year Month Day
2015 10 28
2015 10 29
2015 10 29
2015 10 30
2015 10 30
2015 10 30
2015 11 4
2015 11 5
2015 11 9
2015 11 19
2016 1 31
2016 4 1
我希望获得当年最高年份和相应的最高月份以及当年,月份列的日期
输出:
2016 4 1
如果表格不包含
2016 1 31
2016 4 1
输出的行
2015 11 19
答案 0 :(得分:1)
DECLARE @temp TABLE
(
Y SMALLINT,
M TINYINT,
D TINYINT,
PRIMARY KEY CLUSTERED (Y DESC, M DESC, D DESC) WITH(IGNORE_DUP_KEY=ON)
)
INSERT INTO @temp (Y, M, D)
VALUES
(2015, 10, 28), (2015, 10, 29),
(2015, 10, 29), (2015, 10, 30),
(2015, 10, 30), (2015, 10, 30),
(2015, 11, 4 ), (2015, 11, 5 ),
(2015, 11, 9 ), (2015, 11, 19),
(2016, 1 , 31), (2016, 4 , 1 )
SELECT TOP(1) *
FROM @temp
ORDER BY Y DESC, M DESC, D DESC
结果 -
Y M D
------ ---- ----
2016 4 1
答案 1 :(得分:0)
您可以在sql中使用max函数。
SELECT max(Year) as Year, Month, Day FROM table_name.
希望这有帮助!
答案 2 :(得分:0)
检查此示例。
DECLARE @temp TABLE
(
Y SMALLINT,
M TINYINT,
D TINYINT,
PRIMARY KEY CLUSTERED (Y DESC, M DESC, D DESC) WITH(IGNORE_DUP_KEY=ON)
)
INSERT INTO @temp (Y, M, D)
VALUES
(2015, 10, 28), (2015, 10, 29),
(2015, 10, 29), (2015, 10, 30),
(2015, 10, 30), (2015, 10, 30),
(2015, 11, 4 ), (2015, 11, 5 ),
(2015, 11, 9 ), (2015, 11, 19),
(2016, 1 , 31), (2016, 4 , 1 )
; with cte as
(
select cast ( cast (y as varchar(15)) +'-' + cast (m as varchar(15)) + '-' + cast (m as varchar(15)) as date) dt , y , m, d
from @temp
)
select top 1 y,m,d from cte order by dt desc
delete @temp where y = '2016'
; with cte as
(
select cast ( cast (y as varchar(15)) +'-' + cast (m as varchar(15)) + '-' + cast (m as varchar(15)) as date) dt , y , m, d
from @temp
)
select top 1 y,m,d from cte order by dt desc
答案 3 :(得分:0)
如果您确定这些值代表有效日期,您可以将它们转换为日期并获得MAX:
SELECT DATEPART(year, MAX(CAST(Y as varchar(4)) + RIGHT('0' + CAST(M AS varchar(2)), 2) + RIGHT('0' + CAST(D AS varchar(2)), 2))),
DATEPART(month, MAX(CAST(Y as varchar(4)) + RIGHT('0' + CAST(M AS varchar(2)), 2) + RIGHT('0' + CAST(D AS varchar(2)), 2))),
DATEPART(dd, MAX(CAST(Y as varchar(4)) + RIGHT('0' + CAST(M AS varchar(2)), 2) + RIGHT('0' + CAST(D AS varchar(2)), 2)))
FROM @temp
答案 4 :(得分:0)
这是查询(替换你的表名)
SELECT TOP 1 YEAR, MONTH, DAY
FROM YOUR_TABLE
ORDER BY YEAR DESC, MONTH DESC, DAY DESC