我需要能够为每个具有最大价值的名称选择第一行。
我有一张包含以下内容的表格:
id name value
0 JOHN 123
1 STEVE 125
2 JOHN 127
3 JOHN 126
所以我希望回来:
id name value
1 STEVE 125
2 JOHN 127
关于如何执行此操作的MSSQL语法有任何想法吗?
答案 0 :(得分:7)
指定SQL Server时,未指定版本。如果您使用的是SQL Server 2005或更高版本,则可以执行以下操作:
With RankedItems As
(
Select id, name, value
, Row_Number() Over ( Partition By name Order By value Desc, id Asc ) As ItemRank
From Table
)
Select id, name, value
From RankedItems
Where ItemRank = 1
答案 1 :(得分:2)
尝试:
SELECT
MIN(id) as id,dt.name,dt.value
FROM (SELECT
name,MAX(value) as value
FROM YourTable
GROUP BY name
) dt
INNER JOIN YourTable t ON dt.name=t.name and dt.value=t.value
GROUP BY dt.name,dt.value
尝试一下:
DECLARE @YourTable table (id int, name varchar(10), value int)
INSERT @YourTable VALUES (0, 'JOHN', 123)
INSERT @YourTable VALUES (1, 'STEVE', 125)
INSERT @YourTable VALUES (2, 'JOHN', 127)
INSERT @YourTable VALUES (3, 'JOHN', 126)
--extra data not in the question, shows why you need the outer group by
INSERT @YourTable VALUES (4, 'JOHN', 127)
INSERT @YourTable VALUES (5, 'JOHN', 127)
INSERT @YourTable VALUES (6, 'JOHN', 127)
INSERT @YourTable VALUES (7, 'JOHN', 127)
SELECT
MIN(id) as id,dt.name,dt.value
FROM (SELECT
name,MAX(value) as value
FROM @YourTable
GROUP BY name
) dt
INNER JOIN @YourTable t ON dt.name=t.name and dt.value=t.value
GROUP BY dt.name,dt.value
ORDER BY id
输出:
id name value
----------- ---------- -----------
1 STEVE 125
2 JOHN 127
(2 row(s) affected)
答案 2 :(得分:2)
您可以执行类似
的操作SELECT id, name, value
FROM (SELECT id, name, value
ROWNUMBER() OVER (PARTITION BY name ORDER BY value DESC) AS r
FROM table) AS x
WHERE x.r = 1 ;
这在SQL Server 2000及更早版本中不起作用,但在SQL Server 2005和2008中速度将非常快
答案 3 :(得分:0)
怎么样:
SELECT a.id, a.name, b.maxvalue
FROM mytbl a
INNER JOIN (SELECT id, max(value) as maxvalue
FROM mytbl
GROUP BY id) b ON b.id = a.id
答案 4 :(得分:0)
SELECT a.id, a.name, a.value
FROM mytbl a
INNER JOIN (SELECT name, max(value) as maxvalue
FROM mytbl
GROUP BY name) b ON b.name = a.name and b.maxvalue = a.value