[英]SQL select query using group by
How to get the TeamCount and TeamLead Name currectly 如何正确获取TeamCount和TeamLead名称
Teams | TeamCount | TeamLead Name
-------------------------------------
| Team1 | 2 | NULL
| Team2 | 2 | NULL
| Team1 | 1 | Prashanth
Some times Team may or may not have the team lead. 有时,团队可能没有团队领导。 So we just have to show the TeamLead name as null, if team lead is not found for the team
因此,如果找不到团队负责人,我们只需要将TeamLead名称显示为null
I need some help to get the out as below 我需要一些帮助才能摆脱困境,如下所示
Teams | TeamCount | TeamLead Name
---------------------------------
Team1 | 3 | Prashanth
Team2 | 2 | NULL
...and here you go! ...然后你去!
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;
You should try to develop these solutions by working from the inside out and build the query in steps 您应该尝试从内而外开发这些解决方案,并逐步构建查询
You can do this with a LEFT OUTER join between Team
and TeamMembers
, and including the IsLead
into the join criterion, before grouping by the Team name - this will exclude non-leads: 您可以通过在
Team
和TeamMembers
之间进行LEFT OUTER IsLead
,并将IsLead
包含在IsLead
条件中来进行此操作,然后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;
The TeamCount
doesn't seem to make sense here - if you can elaborate on how you intend deriving it, perhaps we can help here 这里的
TeamCount
似乎没有意义-如果您可以详细说明您打算如何获取它,也许我们可以在这里提供帮助
PS : You've tagged both MySql and Oracle - don't do this please. PS:您已经标记了MySql和Oracle-请不要这样做。
Here you are: 这个给你:
MySQL: 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 http://sqlfiddle.com/#!9/5889d/39
SQl Server: 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
Hope this help. 希望能有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.