使用group by的SQL select查询

时间:2015-07-04 15:37:03

标签: mysql sql oracle group-by

如何最终获得TeamCount和TeamLead名称

  Teams | TeamCount | TeamLead Name
-------------------------------------
| Team1 | 2         | NULL
| Team2 | 2         | NULL
| Team1 | 1         | Prashanth

有时候团队可能会或可能不会有团队领导。 所以我们只需要将TeamLead名称显示为null, 如果没有为团队找到团队负责人

我需要一些帮助才能解决问题

Teams | TeamCount | TeamLead Name
---------------------------------
Team1 | 3         | Prashanth
Team2 | 2         | NULL

3 个答案:

答案 0 :(得分:0)

......在这里你去!

     create table test2 as
            select distinct c.teams,sum(c.TeamCount) as SUM,c.TeamName
     from
           (select a.Teams,a.TeamCount,b.TeamName from team as a
     left outer join
           (select * from team where TeamName ne "") as b
            on a.Teams = B.Teams) as c
     group by c.Teams;

您应该尝试从内到外开发这些解决方案并按步骤构建查询

答案 1 :(得分:0)

您可以在TeamTeamMembers之间使用LEFT OUTER加入,并在加入条件中加入IsLead,然后按团队名称进行分组 - 这将排除非率:

SELECT T.Name, MIN(TM.TName) AS Lead
FROM Teams T
  LEFT OUTER JOIN TeamMembers TM 
    ON TM.TeamId = T.Id AND TM.IsLead = 1
GROUP BY T.Name;

SqlFiddle here

TeamCount似乎没有意义 - 如果你能详细说明你打算如何推导它,也许我们可以在这里提供帮助

PS:你已经标记了MySql和Oracle - 请不要这样做。

答案 2 :(得分:0)

你在这里:

MySQL的:

select team as teamId, sum(teamcount) as teamcount,
  (select teamleadname from teams
   where teamId = teams.team and teamleadname is not null
   limit 1) as teamleadname
from teams
group by team

http://sqlfiddle.com/#!9/5889d/39

SQl服务器:

declare @teams TABLE(Team varchar(20), TeamCount int, TeamLeadName varchar(20));

INSERT INTO @teams
VALUES
    ('Team1', 2, null),
    ('Team2', 2, null),
    ('Team1', 1, 'Prashanth')

select l.Team, l.TeamCount, r.TeamLeadName
from
    (select Team , sum(TeamCount) as TeamCount from @teams group by Team) as l 
    left outer join 
    (select Team, TeamLeadName 
    from 
        (select Team, TeamLeadName, row_number() over(partition by Team order by TeamLeadName desc) as roworder 
        from @teams) as o where o.roworder = 1
    ) as r
    on l.Team = r.Team

希望得到这个帮助。