SQL Server:获得年份和月份

时间:2014-10-22 12:32:53

标签: sql sql-server

我有一个像这样的SQL Server表:

http://sqlfiddle.com/#!2/a15dd/1

我想要做的是显示交易的最新年份和月份。

在这种情况下,我想显示

ID: 1  
Year: 2013  
Month: 11  
Trades: 2

我试图使用:

select 
    id, MAX(year), MAX(month) 
from 
    ExampleTable
where 
    trades > 0
group by 
    id

我是否必须连接列?

4 个答案:

答案 0 :(得分:2)

您可以使用ROW_NUMBER根据相对位置(按订单定义)为每行分配一个数字:

SELECT  ID,
        Year,
        Month,
        Trades,
        RowNum = ROW_NUMBER() OVER(PARTITION BY ID ORDER BY Year DESC, Month DESC)
FROM    ExampleTable
WHERE   Trades > 0;

使用您的示例数据,可以得到:

ID  YEAR    MONTH   TRADES  RowNum
1   2013    11      2       1
1   2013    4       42      2

然后你可以将其限制在RowNum为1:

的位置
SELECT  ID, Year, Month, Trades
FROM    (   SELECT  ID,
                    Year,
                    Month,
                    Trades,
                    RowNum = ROW_NUMBER() OVER(PARTITION BY ID ORDER BY Year DESC, Month DESC)
            FROM    ExampleTable
            WHERE   Trades > 0
        ) AS t
WHERE   t.RowNum = 1;

如果您的示例YearMonth存储为VARCHAR,则需要在订购前转换为INT

RowNum = ROW_NUMBER() OVER(PARTITION BY ID 
                            ORDER BY 
                                CAST(Year AS INT) DESC, 
                                CAST(Month AS INT) DESC)

<强> Example on SQL Fiddle

如果您只对ID为1的记录感到困扰,您只需使用TOP即可:

SELECT  TOP 1 ID, Year, Month, Trades
FROM    ExampleTable
WHERE   ID = 1
AND     Trades > 0
ORDER BY CAST(Year AS INT) DESC, CAST(MONTH AS INT) DESC;

答案 1 :(得分:1)

为什么存储&#34;年&#34;和&#34;月&#34;作为单独的列?在任何情况下,基本逻辑是将两个值组合以获得最新值。这很尴尬,因为您将数字存储为字符串,而月份不是零填充。但它并不那么难:

select id,
       max(year + right('00' + month, 2))
from ExampleTable
group by id;

将它们分开:

select id,
       left(max(year + right('00' + month, 2)), 4) as year,
       right(max(year + right('00' + month, 2)), 2) as month
from ExampleTable
group by id;

Here是一个SQL小提琴。请注意,当您使用SQL Fiddle时,应将数据库设置为正确的数据库。

答案 2 :(得分:1)

我不确定我的问题是否正确,但不应该做以下工作?

  SELECT TOP 1 year + '-' + month AS Last, trades
    FROM ExampleTable
   WHERE CAST(trades AS INTEGER) > 0
ORDER BY CAST(year AS integer) DESC, CAST(month AS integer) DESC

SQLFiddle

答案 3 :(得分:1)

试试这个

SELECT TOP 1  ID, [year], trades,
              MAX(Convert(INT,[month])) OVER(PARTITION BY [year]) AS [Month]
FROM ExampleTable 
WHERE trades > 0