跨三个表的t-sql外连接
我有三个表:
CREATE TABLE person
(id int,
name char(50))
CREATE TABLE eventtype
(id int,
description char(50))
CREATE TABLE event
(person_id int,
eventtype_id int,
duration int)
我想要的是一个查询,它为我提供每个人的每种事件类型的总持续时间的列表,包括所有零条目。例如,如果有 10 个人和 15 种不同的事件类型,则无论事件表的内容如何,都应该返回 150 行。
我可以在两个表之间使用外连接(例如所有事件类型的持续时间),但不能使用第二个外连接。
谢谢!
I have three tables:
CREATE TABLE person
(id int,
name char(50))
CREATE TABLE eventtype
(id int,
description char(50))
CREATE TABLE event
(person_id int,
eventtype_id int,
duration int)
What I want is a single query which gives me a list of the total duration of each eventtype for each person, including all zero entries. E.g. if there are 10 people and 15 different eventtypes, there should be 150 rows returned, irrespective of the contents of the event table.
I can get an outer join to work between two tables (e.g. durations for all eventtypes), but not with a second outer join.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您必须添加 对混合进行 CROSS APPLY 以获得不存在的关系。
You'll have to add a CROSS APPLY to the mix to get the non-existing relations.
您可以交叉连接 person 和 eventtype,然后将结果连接到事件表:
交叉连接是指,对于左表中的每一行,它都连接到右表中的每一行。
You can cross join person and eventtype, and then just join the result to the event table:
A cross join is one where, for each row in the left table, it's joined to every row in the right table.
如果您希望为
person
和eventtype
的每个组合分配一行,则建议使用CROSS JOIN
。为了获取持续时间,我们需要加入event
,但这需要是OUTER
加入,因为可能并不总是有一行。您对“total”的使用表明,对于给定的person
和event
组合,可能存在多个event
,因此我们需要那里还有一个SUM
。示例数据:
查询:
输出:
If you want a row for every combination of
person
andeventtype
, that suggets aCROSS JOIN
. To get the duration we need to join toevent
, but this needs to be anOUTER
join since there might not always be a row. Your use of "total" suggests there there could be more than oneevent
for a given combination ofperson
andevent
, so we'll need aSUM
in there as well.Sample data:
The query:
Output: