我目前正在进行一项查询,以显示我们过去两年所有的完成情况。
这是我的查询
SELECT
SigD.actualCompletionDate,
MONTH(SigD.actualCompletionDate) AS [Month Completed],
YEAR(SigD.actualCompletionDate) AS [Year Completed]
FROM
[BPS].[dbo].tbl_buildLoanSignificantDate AS SigD
INNER JOIN
tbl_buildLoan AS bl ON SigD.BuildloanId = bl.BuildloanId
INNER JOIN
tbl_buildLoanMortgage AS blm ON SigD.BuildloanId = blm.BuildloanId
INNER JOIN
tbl_Broker AS brk ON bl.BrokerId = brk.BrokerId
LEFT JOIN
tbl_firmNetwork AS firm ON brk.firmNetworkID = firm.firmNetworkID
WHERE
SigD.actualCompletionDate BETWEEN '01/01/2016' AND GETDATE()
AND blm.mortgageStatusID = 7
AND bl.caseTypeID = 2
AND firm.name = 'First Complete'
我遇到的问题是显示几个月我们没有完成。
这是我的查询
的结果actualCompletionDate Month Completed Year Completed
------------------------------------------------------
2016-05-12 5 2016
2016-01-21 1 2016
2016-05-26 5 2016
2016-04-12 4 2016
2016-08-22 8 2016
2017-07-26 7 2017
2016-05-19 5 2016
我想要的是显示这些年的每个月(2016年和2017年);如果那个月没有完成,那么我需要在那个月显示0
。
我希望我在这里解释过自己。
干杯 生锈
答案 0 :(得分:1)
要显示0在哪里?您只需加入包含所有预期日期的派生表:
SELECT COALESCE(p.actualCompletionDate,<DefaultDate>) as actualCompletionDate,
--replace <defaultDate> with what you want to show if there's no data in this month
[s.Month],
[s.Year]
FROM (SELECT '1' as [month],'2016' as [year]
UNION ALL
SELECT '2' ,'2016'
.... --As many dates as you need
) s
LEFT JOIN (Your Query Here) p
ON(p.month = s.[month completed] AND p.year = s.[year completed]
答案 1 :(得分:1)
;WITH FULLDATE AS (
SELECT * FROM
(VALUES(2016),(2017)) YEARS(Y) CROSS JOIN
(VALUES(1),(2),(3),(4),(5),(6),(7),(8),(9),(10),(11),(12)) MONTHS(M)
)
SELECT
X.actualCompletionDate,
F.M AS [Month Completed],
F.Y AS [Year Completed]
FROM
FULLDATE F
LEFT JOIN (
SELECT
SigD.actualCompletionDate,
Month(SigD.actualCompletionDate) AS [Month Completed],
YEAR(SigD.actualCompletionDate) AS [Year Completed]
FROM
[BPS].[dbo].tbl_buildLoanSignificantDate AS SigD
INNER JOIN tbl_buildLoan AS bl ON SigD.BuildloanId = bl.BuildloanId
INNER JOIN tbl_buildLoanMortgage AS blm ON SigD.BuildloanId = blm.BuildloanId
INNER JOIN tbl_Broker AS brk ON bl.BrokerId = brk.BrokerId
INNER JOIN tbl_firmNetwork AS firm ON brk.firmNetworkID = firm.firmNetworkID
WHERE SigD.actualCompletionDate BETWEEN '01/01/2016' AND GETDATE()
and blm.mortgageStatusID = 7
and bl.caseTypeID = 2
and firm.name = 'First Complete'
) AS X ON F.M = X.[Month Completed] AND F.Y = X.[Year Completed]
ORDER BY F.Y , F.M