如何创建一个合并来自多个表的信息的视图?

时间:2013-09-04 09:01:54

标签: sql sql-server

我把这个例子编成了与我正在处理的情况类似的情况。

输入表:

团队表

TeamID | TeamName
=================
     1 | Alpha
     2 | Beta
     3 | Charlie
     4 | Delta

会员表

TeamID | MemberID | MemberName | Age
====================================
     1 |        1 | Anne       |  10
     1 |        2 | Bob        |  20
     2 |        1 | Carol      |  30
     2 |        2 | David      |  40
     3 |        1 | Elaine     |  30
     3 |        2 | Fred       |  20
     4 |        1 | Geoff      |  50

职位表

TeamID | JobID | Earned | Status
===================================
     1 |     1 |    50  | Complete
     1 |     2 |    75  | InProgress
     2 |     1 |    80  | Complete
     3 |     1 |    50  | InProgress

我正在尝试创建一个视图,该视图整合了来自这3个输入表的信息:

TeamID | TeamName | IsAbove35 | HasBeenPaid | AllJobsComplete
===============================================================
     1 | Alpha    |         0 |           1 |                0
     2 | Beta     |         1 |           1 |                1
     3 | Charlie  |         0 |           1 |                0
     4 | Delta    |         1 |           0 |                0

IsAbove35 如果任何团队成员年龄超过35岁,则应包含1(否则为0)

如果团队的收入超过0,

HasBeenPaid 应该包含1

AllJobsComplete 如果团队有任何作业条目并且一切都完整,则应该包含1

我可以找出如何单独完成某些部分,例如

IsAbove35

select t.TeamID,
case when m.Age is null then 0 else 1 end as IsAbove35
from Team t left outer join Member m
on t.TeamID = m.TeamID
and Age > 35

HasBeenPaid

select t.TeamID, case when SUM(Earned) > 0 then 1 else 0 end as HasBeenPaid
from Team t left outer join Job j
on t.TeamID = j.TeamID
group by t.teamid

但我不确定如何计算字段'AllJobsComplete'以及如何将所有这些列放在一起进行视图。

任何帮助都非常感谢!

1 个答案:

答案 0 :(得分:1)

这样做的一种方法是在CASE语句中使用相关的子查询:

SELECT 
* 
, CASE WHEN EXISTS 
    (SELECT * FROM dbo.Member m WHERE m.TeamID = t.TeamID AND m.Age > 35) 
   THEN 1 ELSE 0 END AS IsAbove35 
, CASE WHEN (SELECT SUM(Earned) FROM Job j WHERE j.TeamID = t.TeamID) > 0
   THEN 1 ELSE 0 END AS HasEarnings
, CASE WHEN EXISTS
    (SELECT * FROM Job j WHERE j.TeamID = t.TeamID AND Status = 'Complete')
    AND NOT EXISTS 
    (SELECT * FROM Job j WHERE j.TeamID = t.TeamID AND Status <> 'Complete')
   THEN 1 ELSE 0 END AS AllJobsComplete
FROM dbo.Team t

<强> SQLFiddle DEMO