SQL请求:如何使用多表和calcul进行特定选择?

时间:2011-08-18 15:59:58

标签: sql oracle

这是我的问题。我在Oracle数据库上有4个表:

  • 团队(teamID,teamName)
  • TeamMembers(membersID,teamID,membersStatusID)
  • 成员(membersID,membersName)
  • 状态(membersStatusID,statusName)

我需要获取teamName,这些团队中teamMembers的数量以及状态为“队长”的成员的姓名......所有这些都在一个{{1}中在SQL中。

这个问题很长时间没有解决方案......任何想法?

编辑:我需要查看所有团队,即使其中没​​有成员。

4 个答案:

答案 0 :(得分:0)

我的oracle上有点生疏,所以这里可能会有一些轻微的语法问题,但我会试一试:

SELECT t.teamName,
  count(*) AS teamMembers,
  c.membersName as teamCaptain
FROM team t
  INNER JOIN TeamMembers tm ON tm.teamID = t.teamID
  LEFT JOIN Members m ON m.membersID = tm.membersID
  LEFT JOIN TeamMembers tmc ON tmc.teamID = t.teamID AND tmc.memberStatusID = "Captain"
  LEFT JOIN Members c ON c.membersID = tmc.membersID
  GROUP BY t.teamName, c.membersName

编辑:忘记GROUP BY行!

答案 1 :(得分:0)

select t.team_id, t.teamName, count(tm.teamid), m.membersname
from team t, teammembers tm, members m, status s
where t.teamid = tm.teamid (+)
and tm.membersid = m.membersid (+)
and m.membersstatusid = s.statusid (+)
and s.statusname = 'Captain'
group by t.team_id, t.teamName, m.membersname

答案 2 :(得分:0)

SELECT
teamName,
b.[Number Of Members],
c.membersName AS [Captian]
FROM
Team
LEFT JOIN
(
SELECT
    COUNT(*) AS [Number Of Members],
    teamID
FROM
    TeamMembers
GROUP BY
    teamID
) AS b ON Team.teamID = c.teamID
LEFT JOIN
(
SELECT
    membersName,
    teamID
FROM
    Members
INNER JOIN
    TeamMembers ON Members.membersID = TeamMembers.membersID
INNER JOIN
    Status ON TeamMembers.memberStatusID = Status.memberStatusID AND Status.statusName = 'Captian'
) AS c ON c.teamID = Team.teamID

可以工作。可能需要调整它,因为b select语句中的group by。我也只是在sql中写这个,因为我不知道oracle语法

答案 3 :(得分:0)

我现在无法测试此选择,但你可以试试这个:

select team.teamName,count(distinct members.membersID) numMembers,
MAX(CASE when status.statusName='CAPTAIN' then members.membersname else null END) Captain
from team,teammembers,members,status 
where team.teamID=teammembers.teamID(+)
and teammembers.membersID=members.membersID(+)
and teamMembers.memberStatusID=status.memberstatusID(+)
group by team.teamName;