我正在尝试根据SQL Server 2008中特定列值的最大值选择行。我需要根据最大版本选择书名和年份。
当前表格数据:
BookName Year Edition
Latest Science 2013 1
Latest Science 2014 2
Latest Science 2015 3
Easy Maths 2014 1
Easy Maths 2015 2
Magic vs Logic 2015 1
输出应为:
BookName Year Edition
Latest Science 2015 3
Easy Maths 2015 2
Magic vs Logics 2015 1
我试过了,但只产生了整行的一行
SELECT Book, year, edition
FROM Book_info
where edition=(select max(edition) from book_info)
答案 0 :(得分:1)
我会这样做:
;WITH cte AS (
SELECT *,
ROW_NUMBER() OVER (PARTITION BY BookName ORDER BY Edition DESC) AS rn
FROM book_info
)
SELECT * FROM cte
WHERE rn=1
答案 1 :(得分:0)
你应该通过有条款来查找分组。
以下是符合您要求的整个脚本,它会返回您正在寻找的结果。
USE [Test]
--table
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Book](
[Id] [int] IDENTITY(1,1) NOT NULL,
[BookName] [varchar](50) NOT NULL,
[Year] [int] NOT NULL,
[Edition] [int] NOT NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
USE [Test]
GO
--records
INSERT INTO [dbo].[Book]
([BookName]
,[Year]
,[Edition])
VALUES
('Last Science', 2013 ,1),
('Last Science', 2014 ,2),
('Last Science', 2015 ,3),
('Easy Maths', 2014 ,1),
('Easy Maths', 2015 ,2),
('Magic vs Logic', 2015 ,1)
GO
USE [Test]
GO
--query
SELECT
BookName,
MAX([Year]) AS Year,
MAX(Edition) AS Edition
FROM dbo.Book
GROUP BY
BookName
Order by MAX(Edition) DESC