简体   繁体   English

如何联接多个表,而不忽略不匹配的值

[英]How to join multiple tables, without omitting values without a match

This small example is based on a question that I have run into countless times, however I failed finding the best answer. 这个小例子基于一个我无数次遇到的问题,但是我找不到最佳答案。

I would like to create a report on Incidents logged per type, per month. 我想创建有关每种类型每月记录的事件的报告。 Written the following query. 编写以下查询。

SELECT
    d.MonthPeriod
    ,i.[Type]
    ,COUNT(*) AS [Count of Calls]
FROM
    [dbo].[FactIncident] as i
        LEFT JOIN
    [dbo].[DimDate] as d on i.DateLoggedKey = d.DateKey
GROUP BY
    d.[MonthPeriod],
    i.[Type]

This results in the following: 结果如下:

在此处输入图片说明

Although correct, I would like to visualize earlier months with 0 logged calls. 虽然正确,但我想将0个已记录的呼叫显示在前几个月。 DimDate contains the following. DimDate包含以下内容。

在此处输入图片说明

What is the best and/or most efficient way of showing the count of calls per month, per type, for all months. 显示所有月份每月每种类型的呼叫次数的最佳和/或最有效的方法是什么。 Even if the count is 0? 即使计数为0?

Thought of using Cross Apply, however the resultant query gets huge quickly. 考虑使用Cross Apply,但是结果查询迅速变得庞大。 Only think of a dataset requiring the count of calls per customer, per category, per month over the last 3 years.. 仅考虑一个数据集,该数据集需要过去三年中每个客户每个类别每个月的呼叫计数。

Any ideas? 有任何想法吗?

Do the left join starting with the calendar table, so you keep all the months: 从日历表开始进行left join ,因此保留所有月份:

SELECT d.MonthPeriod, i.[Type], COUNT(i.type) AS [Count of Calls]
FROM [dbo].[DimDate] d LEFT JOIN
     [dbo].[FactIncident] i
     ON i.DateLoggedKey = d.DateKey
GROUP BY d.[MonthPeriod], i.[Type];

This will, of course, return the type as NULL for the months with no data. 当然,这将在没有数据的月份中将type返回为NULL

If you want all types present, then use CROSS JOIN on the types. 如果要显示所有类型,请在这些类型上使用CROSS JOIN This example gets the data from the fact table, but you might have another reference table containing each type: 本示例从事实表获取数据,但是您可能还有另一个包含每种类型的参考表:

SELECT d.MonthPeriod, t.[Type], COUNT(i.type) AS [Count of Calls]
FROM [dbo].[DimDate] d CROSS JOIN
     (select distinct type from factincident) t LEFT JOIN
     [dbo].[FactIncident] i
     ON i.DateLoggedKey = d.DateKey and i.type = t.type
GROUP BY d.[MonthPeriod], t.[Type];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM