我需要在连接其他表并对它们进行计数计算时加入一个表。我顺便使用SQL Server 2008 R2。
当前状态 - 我有三个表MergedSessionsID,EventsSeparated和EventsDescriptions。
MergedSessionsID,这是我操纵数据的地方 - 会话主要是通过指定公司名称和会话时间(参见下面的数据示例)。
EventsSeparated表链接MergedSessionsID。基本上会话可以有一个或多个事件。
EventsDescription表包含事件的描述,例如这个和那个发生在用户身上。
我的目标是了解在一段时间内发生的事件总数。图表1是运行以下查询的结果。
但是,我还希望将旧数据与新数据进行比较,并查看事件数量的变化情况。因此,如图2所示,这就是我想象的结果 - 在2210年3月向PreCounter展示数据,在2210年4月向PostCounter展示数据。
实施此方法的最佳方法是什么?
SELECT E.[Event]
,COUNT(1) AS Counter
,ED.[Event Description]
FROM [ShipCompanies].[dbo].MergedSessionsID AS S
INNER JOIN [ShipCompanies].dbo.EventsSeparated AS E
ON S.ID = E.ID
INNER JOIN [ShipCompanies].dbo.EventDescription AS ED
ON E.[Event] = ED.[Unique ID]
WHERE S.Company = 'SuperSpaceShipOne'
AND S.[Session Time] BETWEEN '2210-03-02' AND '2210-03-05'
GROUP BY E.[Event], ED.[Event Description]
ORDER BY E.[Event]
SELECT * FROM MergedSessionsID
ID Company Session Time
1 SuperSpaceShipOne 2210-03-05
2 SuperSpaceShipOne 2210-03-03
3 SuperSpaceShipOne 2210-03-02
4 SuperSpaceShipOne 2210-04-01
5 SuperSpaceShipOne 2210-04-02
6 SuperSpaceShipOne 2210-04-03
SELECT * FROM EventsSeparated
ID Event
1 2000
2 2001
2 2002
3 2001
4 2002
5 2002
6 2002
SELECT * FROM EventDescription
Unique ID Event Description
2000 'User Entered the Pod'
2001 'User Initiated Launching Sequence'
2002 'User Error encountered'
图表1.合并输出汇总表(我现在拥有的)
Event Counter Event Description
2000 1 'User Entered the Pod'
2001 2 'User Initiated Launching Sequence'
2002 1 'User Error encountered'
图表2.合并输出汇总表(我想要的内容)
Event PreCounter Event Description PostCounter
2000 1 'User Entered the Pod' 0
2001 2 'User Initiated Launching Sequence' 0
2002 1 'User Error encountered' 3
答案 0 :(得分:1)
Select E.[Event]
, Sum( Case
When S.[Session Time] Between '2210-03-02' And '2210-03-05' Then 1
Else 0 End ) As PreCounter
, Sum( Case
When S.[Session Time] Between '2210-04-02' And '2210-04-05' Then 1
Else 0 End ) As PostCounter
, ED.[Event Description]
From [ShipCompanies].[dbo].MergedSessionsID As S
Join [ShipCompanies].dbo.EventsSeparated As E
On S.ID = E.ID
Join [ShipCompanies].dbo.EventDescription As ED
On E.[Event] = ED.[Unique ID]
Where S.Company = 'SuperSpaceShipOne'
And (
S.[Session Time] Between '2210-03-02' And '2210-03-05'
Or S.[Session Time] Between '2210-04-02' And '2210-04-05'
)
Group By E.[Event], ED.[Event Description]
Order By E.[Event]