MS SQL将max() - 1添加到qyery

时间:2018-05-22 10:33:14

标签: sql sql-server

如何添加查询max(o.Acct)-1行。我需要可视化最后两个o.Acct行。我的查询目前只显示max(o.Acct)

SELECT Max(o.Acct) AS [MaxAcct],o.ObjectID,o.Opertype
FROM Operations o
GROUP By o.ObjectID,o.Opertype

2 个答案:

答案 0 :(得分:1)

如果您想查看最后两行(每组),最好使用ROW_NUMBER()而不是GROUP BY

SELECT
  *
FROM
(
  SELECT
    *,
    ROW_NUMBER() OVER (PARTITION BY ObjectID,
                                    Opertype
                           ORDER BY Acct DESC
                      )
                         AS sequence_id
  FROM
    Operations
)
  sortedOperations
WHERE
  sequence_id <= 2
ORDER BY
  ObjectID,
  Opertype,
  Acct

答案 1 :(得分:0)

如果你想要最后两件事,我会想order bytop。像这样:

select top (2) o.*
from Operations o
order by o.acct desc;