Sql 如何在每个有条件的组中选择最大值
如何在多个列上选择分组数据的最大值记录,其中组的正项数>负项数Sql 如何在每个有条件的组中选择最大值,sql,sql-server-2008,greatest-n-per-group,Sql,Sql Server 2008,Greatest N Per Group,如何在多个列上选择分组数据的最大值记录,其中组的正项数>负项数 Name,Marks,ID,Location steve, 5 1 irving steve, 2 2 irving steve, 6 3 toledo steve, 3 4 irving steve, 1 5 irving john, 6 1 london john, 4 2 london john, 1 3 hills abhi, -2
Name,Marks,ID,Location
steve, 5 1 irving
steve, 2 2 irving
steve, 6 3 toledo
steve, 3 4 irving
steve, 1 5 irving
john, 6 1 london
john, 4 2 london
john, 1 3 hills
abhi, -2 1 akron
abhi, -3 2 akron
abhi, 2 3 akron
abhi, -5 4 akron
abhi, 1 5 market
这里我想选择同一个人的最大id和位置,其中正面标记数>负面标记数。
谁能帮帮我吗?这应该能帮到你。我为测试创建了临时表。我添加了几行数据来测试您请求的额外过滤。我不确定你是否想看到记录的数量,所以我把它们注释掉了,所以如果你想要的话,它就在那里
CREATE TABLE #aa(
[Name] VARCHAR(10),
Marks int,
ID int,
[Location] VARCHAR(20));
INSERT #aa ([Name],Marks,ID,[Location])
VALUES ('steve',5,1,'irving'),
('steve',2,2,'irving'),
('steve',6,3,'toledo'),
('steve',3,4,'irving'),
('steve',1,5,'irving'),
('steve',1,6,'irving'),
('john',6,1,'london'),
('john',4,2,'london'),
('john',1,3,'hills'),
('john',5,4,'london'),
('john',2,5,'hills'),
('abhi',-2,1,'akron'),
('abhi',-3,2,'akron'),
('abhi',2,3,'akron'),
('abhi',-5,4,'akron'),
('abhi',1,5,'market');
--Common Table Expression (CTE) to get groups with more positive marks
WITH groupValue AS
( SELECT [Name],[Location]--,Count(*) AS 'Records'
FROM #aa
GROUP BY [Name],[LOCATION]
HAVING SUM(CASE WHEN Marks > 0 THEN 1 ELSE -1 END) > 0
AND Count(*) <> 1 -- Making sure the total records is greater than 1
AND Count(*) % 2 <> 0 --Finding odd numbers by dividing by 2 and
-- checking the remainder. Even numbers will
-- always have a remainder of 0.
)
SELECT a.[Name],a.[Location],MAX(ID) 'MaxId'--,groupValue.Records
FROM groupValue
JOIN #aa a ON groupValue.Name = a.Name
AND groupValue.Location = a.Location
GROUP BY a.[NAME],a.[Location]--,groupValue.Records
ORDER BY a.[NAME],a.[Location]
DROP TABLE #aa
请不要发布代码图片的链接。编辑问题并作为文本输入。谢谢,谢谢,杰森,它在工作。我还需要一个条件,以便仅为具有多条记录和奇数条记录的组选择max ID,用于上述查询。我现在正在使用它。