目前我查询我的数据库以查找特定日期参数内的所有交互。我还将我的InteractionAttendees加入该表,然后通过TargetGroups表加入它。 InteractionAttendees告诉我谁参加了互动,TargetGroup告诉我这个人,他们是否是目标群体的一部分,如土着或法语。
我在设置原住民和法语国家专栏时遇到了麻烦。如果TargetGroup表中有任何与会者,我想将其设置为true。
select CONVERT(date, getdate()) as ActivityDate,
CASE when Type = 0 Then 'General'
when Type = 1 Then 'Activity'
else 'Task' End as Type,
CASE when Indepth = 0 Then 'False' else 'True' End as Indepth,
Subject,
Comments,
'false' as Aboriginal,
'false' as FrancoPhone,
'false' as Female,
'false' as Youth,
'false' as Other
from Sarnia.dbo.Interactions as X
full outer join sarnia.dbo.InteractionAttendees as Y on X.Id = Y.Interaction_Id
full outer join Sarnia.dbo.TargetGroups as Z on Y.Person_Id = Z.PersonId
where ActivityDate >= '2015-07-01' and ActivityDate <= '2015-09-30'
group by ActivityDate, Type, Indepth, Created, subject, comments
例如
Interaction Table
Id
1
Interaction Attendee Table
Id InteractionId PersonId
1 1 5
2 1 10
TargetGroups Table
Id PersonId TargetValue
1 5 Aboriginal
2 10 Francophone
所以我的结果表是
Activity Date Aboriginal Francophone
---- True True
请问如何正确填充目标组列。
答案 0 :(得分:1)
您可以像这样更新您的查询:以老式的方式进行透视。基于您之前的问题,我假设它是一个sql server DB。
MAX(IIF(TargetValue = 'Aboriginal', 'True', 'False')) as Aboriginal,
MAX(IIF(TargetValue = 'FrancoPhone', 'True', 'False')) as FrancoPhone
如果你有SQL Server 2008或更早版本,你可以使用类似这样的东西
MAX(CASE WHEN TargetValue = 'Aboriginal' THEN 'True' ELSE 'False' END) as Aboriginal,
MAX(CASE WHEN TargetValue = 'FrancoPhone' THEN 'True' ELSE 'False' END) as FrancoPhone
答案 1 :(得分:0)
以下是如何使用CTE执行此操作的示例。注意,我将此添加到您给出的示例sql中,但该sql有很多错误。
with igroup as
(
SELECT IID,
CASE WHEN ACOUNT > 0 THEN true ELSE false END AS Aboriginal,
CASE WHEN FCOUNT > 0 THEN true ELSE false END AS Francophone
FROM (
SELECT InteractionId as IID,
SUM(CASE WHEN TargetValue = 'Aboriginal' THEN 1 ELSE 0 END) as ACOUNT,
SUM(CASE WHEN TargetValue = 'FrancoPhone' THEN 1 ELSE 0 END) as FCOUNT
FROM sarnia.dbo.InteractionAttendees A
LEFT JOIN sarnia.dbo.TargetGroups as G on A.Person_Id = G.PersonId
GROUP BY InteractionId
) X
)
select CONVERT(date, getdate()) as ActivityDate,
CASE when Type = 0 Then 'General'
when Type = 1 Then 'Activity'
else 'Task' End as Type,
CASE when Indepth = 0 Then 'False' else 'True' End as Indepth,
Subject,
Comments,
igroup.Aboriginal,
igroup.FrancoPhone,
from Sarnia.dbo.Interactions as X
full outer join sarnia.dbo.InteractionAttendees as Y on X.Id = Y.Interaction_Id
join igroup on X.Id = igroup.IID
where ActivityDate >= '2015-07-01' and ActivityDate <= '2015-09-30'
group by ActivityDate, Type, Indepth, Created, subject, comments