我需要使用SQL Server 2008按目标分析镜头,命中和事件的数量。如果镜头击中目标,则有可能发生事件。我想知道最后一次比赛的日期,以及自上次比赛以来有多少次击中目标。
我的输入表有点像这样:
TargetList
Site_Code Target_Code WEIGHT Client
SiteA 00001 1 ClientName
SiteA 00002 1 ClientName
SiteA 00003 1 ClientName
SiteA 00004 1 ClientName
Attempts
ID Start_Time Client Target_Code
ID-0001 2017-01-24 01:35:30.000 ClientName 00001
ID-0002 2017-01-24 02:35:30.000 ClientName 00001
ID-0003 2017-01-24 03:35:30.000 ClientName 00001
ID-0004 2017-01-24 04:35:30.000 ClientName 00001
ID-0005 2017-01-24 05:35:30.000 ClientName 00001
ID-0006 2017-01-24 06:35:30.000 ClientName 00001
ID-0007 2017-01-24 07:35:30.000 ClientName 00001
ID-0008 2017-01-24 08:35:30.000 ClientName 00001
ID-0009 2017-01-24 09:35:30.000 ClientName 00001
ID-0010 2017-01-24 10:35:30.000 ClientName 00001
ID-0011 2017-01-24 11:35:30.000 ClientName 00001
ID-0012 2017-01-24 12:35:30.000 ClientName 00001
Hits
ID AttemptID Datetime ClientName TargetCode HitType
HT-0001 ID-0002 2017-01-24 02:35:30.000 ClientName 00001 Z5
HT-0002 ID-0003 2017-01-24 03:35:30.000 ClientName 00001 A1
HT-0003 ID-0004 2017-01-24 04:35:30.000 ClientName 00001 B5
HT-0004 ID-0006 2017-01-24 06:35:30.000 ClientName 00001 Z5
--Most recent Event below
HT-0005 ID-0008 2017-01-24 16:35:30.000 ClientName 00001 Z5
--4 Hits since the last Z5 event
HT-0006 ID-0009 2017-01-24 09:35:30.000 ClientName 00001 A1
HT-0007 ID-0010 2017-01-24 10:35:30.000 ClientName 00001 A1
HT-0008 ID-0011 2017-01-24 11:35:30.000 ClientName 00001 A1
HT-0009 ID-0012 2017-01-24 12:35:30.000 ClientName 00001 A1
我的预期输出:
SiteCode TargetCode CountOfAttempts CountofHits LastEvent HitsSinceLastEvent
SiteA 00001 12 9 2017-01-24 16:35:30.000 4
到目前为止,我的查询是:
select bp.Site_Code 'Site'
, bp.Target_Code 'Target'
, COUNT(ca.id) 'Count of Attempts'
, COUNT(htt.id) 'Count of Hits'
, lst.[Last Event] 'Last Event'
from (select Site_Code, Target_Code
from TargetList t
where t.WEIGHT > 0
and Client = 'ClientName') as bp
left join Attempts ca on bp.Target_Code = ca.Target_Code and ca.START_TIME > '20170130' and ca.Client = 'ClientName'
Left join HitInformation htt on htt.Attemptid = ca.id
left join (select ht.TargetCode 'Target'
, max(ht.datetime) 'Last Event'
from HitInformation ht
where rc.Client = 'ClientName'
and ht.DATETIME > '20170101'
and ht.HitType = 'Z5'
group by ht.TargetCode
) as lst on lst.TargetCode= bp.Target_Code
group by bp.Site_Code, bp.Target_Code, lst.[Last Event]
order by COUNT(ht.id)desc
我使用子查询来确定Z5命中的最后一个实例,但是我很难理解如何获得自上次事件以来的命中数。
我的谷歌努力包括“自事件sql服务器以来查找总数”和“按行特定日期sql服务器总计”的变体,但我没有提出任何相关内容。
我提前感谢您提供任何帮助。