如何在具有条件

时间:2017-04-30 00:57:16

标签: 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   1   akron
abhi,  -3   2   akron
abhi,   2   3   akron
abhi,  -5   4   akron
abhi,   1   5   market

这里我想选择同一个人的最大ID和阳性标记数量的位置>负数的数量。 有人可以帮帮我吗?

1 个答案:

答案 0 :(得分:0)

这应该会帮助你。我创建了临时表进行测试。我添加了几行数据来测试您请求的额外过滤。我不确定你是否想看到记录的数量,所以我对它们进行了评论,所以如果你想要的话它就在那里。

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