我有一个SQL查询,但我想显示几个月,没有条目。现在只需输入条目即可。这是代码:
SELECT YEAR(T0.[Recontact]) AS 'Év', MONTH(T0.[Recontact]) AS 'Hónap',
T1.[SlpName], COUNT(T0.[ClgCode]) AS 'Tárgyalások'
FROM OCLG T0
INNER JOIN OSLP T1 ON T0.[SlpCode] = T1.[SlpCode]
WHERE T0.[Action] = 'M' AND
T0.[Recontact] >= 'date' AND
T0.[Recontact] <= 'date2' AND
T1.[SlpName] = 'user name'
GROUP BY YEAR(T0.[Recontact]), MONTH(T0.[Recontact]), T1.[SlpName]
ORDER BY 1,2
答案 0 :(得分:1)
如果您的数据中完全没有年份+月份,则您需要在可以在该位置显示的某处构建一个空行。您可以创建日历表(每天一行)或月表(每月一行)。那也可以是&#34;虚拟&#34;计算表以CTE或类似方式构建。
一旦你有了这个,你可以这样做:
select
M.Year, M.Month, X.SlpName, isnull(X.CODES,0) as CODES
from
months M
outer apply (
SELECT
YEAR(T0.[Recontact]) as Year,
MONTH(T0.[Recontact]) AS Month,
T1.[SlpName],
COUNT(T0.[ClgCode]) AS CODES
FROM OCLG T0
INNER JOIN OSLP T1 ON T0.[SlpCode] = T1.[SlpCode]
WHERE T0.[Action] = 'M' AND
T0.[Recontact] >= 'date' AND
T0.[Recontact] <= 'date2' AND
T1.[SlpName] = 'user name'
GROUP BY YEAR(T0.[Recontact]), MONTH(T0.[Recontact]), T1.[SlpName]
) X on X.Year = M.Year and X.Month = M.Month
where M.MONTHDATE >= 'date' and M.MONTHDATE <= 'date2'
ORDER BY 1,2
这是一个假想的月份表,其中包含年,月和月日期列,日期是该月的第一天 - 您仍然需要检查您提取的范围是否正确
我还没有对此进行测试,但它应该有效。
答案 1 :(得分:0)
在请求中用LEFT JOIN替换INNER JOIN以获得NULL结果。
SELECT YEAR(T0.[Recontact]) AS 'Év', MONTH(T0.[Recontact]) AS 'Hónap',
T1.[SlpName], COUNT(T0.[ClgCode]) AS 'Tárgyalások'
FROM OCLG T0
LEFT JOIN OSLP T1 ON (T0.[SlpCode] = T1.[SlpCode]
AND T1.[SlpName] = 'user name')
WHERE T0.[Action] = 'M'
AND T0.[Recontact] >= 'date'
AND T0.[Recontact] <= 'date2'
GROUP BY YEAR(T0.[Recontact]), MONTH(T0.[Recontact]), T1.[SlpName]
ORDER BY 1,2
答案 2 :(得分:0)
在请求中用LEFT JOIN替换INNER JOIN以获得NULL结果。 了解更多访问: http://academy.comingweek.com/sql-groupby-clause/