1

我已经将这个示例作为与我正在处理的示例类似的情况。

输入表:

团队表

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

我可以弄清楚如何单独做一些部分,例如

高于 35

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

已经支付

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”字段以及如何将所有这些列放在一个视图中。

非常感谢任何帮助!

4

1 回答 1

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 演示

于 2013-09-04T09:18:54.727 回答