我有3张桌子:
致电表:
+-----------+-------------+
| CallId | CallerName |
+-----------+-------------+
| A | Alice |
| B | Bruno |
| C | Tina |
| D | Marina |
| E | Elena |
+-----------+-------------+
AnsweredCall表
+-----------+-------------+
| CallId | PhoneNumber |
+-----------+-------------+
| A | 1234567 |
| B | 45678 |
| C | 1598 |
+-----------+-------------+
AllCallsDetail表:
+--------+--------+-------+-------------+
| CallId | Caller | Callee| CallType |
+--------+--------+-------+-------------+
| A | 1234 | 1111 | 1 |
| B | 4567 | 2222 | 2 |
| C | 8927 | -1 | 2 |
| D | 4567 | 2562 | 2 |
| E | 8927 | -1 | 1 |
+--------+--------+-------+-------------+
我必须创建一个视图,其中包含与AnsweredCall表连接的Call表中的所有记录(其中存在值,不存在,显示为null)并与AllCallsDetails一起使用我必须显示由CallTypeId过滤的两个列。 第一列如下:
(SELECT allCalls.Caller Where (allCalls.CallType= 1)) as Caller
第二栏如下:
(SELECT allCalls.Callee Where (allCalls.ConferenceType!= 1 and allCalls.Callee != '-1')) as Callee
现在我有类似的东西,但Callee列始终为null,我不明白为什么,因为Caller列包含良好的值。
Create VIEW [dbo].[CallView]
as
Select NEWID() As Id
,callTbl.CallId
,callTbl.CallerName
,answeredCallTbl.PhoneNumber
,(SELECT callDetailTbl.Caller Where(callDetailTbl.CallType = 1)) as Caller
,(SELECT callDetailTbl.Callee Where (callDetailTbl.CallType != 1 and callDetailTbl.Callee != '-1')) as Callee
FROM [dbo].[Call] as callTbl
left join [dbo].[AnsweredCall] answeredCallTbl on callTbl.CallId= answeredCallTbl .CallId
left join [dbo].[AllCallsDetails] callDetailTbl on callTbl.CallId= callDetailTbl .CallId
输出必须如下:
+----+--------+------------+-------------+--------+-------+
| Id | CallId | CallerName | PhoneNumber | Caller | Calle |
+----+--------+------------+-------------+--------+-------+
| 1 | A | Alice | 1234567 | 1234 | null |
| 2 | B | bruno | 45678 | null | 2222 |
| 3 | C | tina | 1598 | null | null |
| 4 | D | Marina | null | null | 2562 |
| 5 | E | Elena | null | 8927 | null |
+----+--------+------------+-------------+--------+-------+
答案 0 :(得分:1)
您可以使用CASE
语句,例如
Create VIEW [dbo].[CallView]
as
Select NEWID() As Id
,callTbl.CallId
,callTbl.CallerName
,answeredCallTbl.PhoneNumber
,case when coalesce(callDetailTbl.CallType, 0) = 1 then callDetailTbl.Caller end as Caller
,case when (coalesce(callDetailTbl.CallType,0) != 1 and coalesce(callDetailTbl.Callee, '') != '-1') then callDetailTbl.Callee end as Callee
FROM [Call] as callTbl
left join [AnsweredCall] answeredCallTbl on callTbl.CallId= answeredCallTbl .CallId
left join [AllCallsDetail] callDetailTbl on callTbl.CallId= callDetailTbl .CallId