![](/img/trans.png)
[英]Concatenate or join multiple tables to a single table in CodeIgniter 3 without omitting rows if there is an empty cell
[英]How to join multiple tables, without omitting values without a match
這個小例子基於一個我無數次遇到的問題,但是我找不到最佳答案。
我想創建有關每種類型每月記錄的事件的報告。 編寫以下查詢。
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]
結果如下:
雖然正確,但我想將0個已記錄的呼叫顯示在前幾個月。 DimDate包含以下內容。
顯示所有月份每月每種類型的呼叫次數的最佳和/或最有效的方法是什么。 即使計數為0?
考慮使用Cross Apply,但是結果查詢迅速變得龐大。 僅考慮一個數據集,該數據集需要過去三年中每個客戶每個類別每個月的呼叫計數。
有任何想法嗎?
從日歷表開始進行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];
當然,這將在沒有數據的月份中將type
返回為NULL
。
如果要顯示所有類型,請在這些類型上使用CROSS JOIN
。 本示例從事實表獲取數據,但是您可能還有另一個包含每種類型的參考表:
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.