2015-12-02 109 views
-1

我有一張桌子,年份,月份,日期如下。如何獲得最大列使用SQL?

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

你的意思是你想每年的最新日期? –

+0

爲什麼不以desc命令? –

回答

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 
0

可以在SQL中使用最多的功能。

SELECT max(Year) as Year, Month, Day FROM table_name. 

希望得到這個幫助!

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 
0

如果你一定值代表有效日期,您可以將它們轉換爲日期,並獲得最大的是:

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 
0

下面是該查詢(更換你的表名)

SELECT TOP 1 YEAR, MONTH, DAY 
FROM YOUR_TABLE 
ORDER BY YEAR DESC, MONTH DESC, DAY DESC