我有一个查询,它应该使用同一数据库中的两个表之间的连接函数来创建一个临时表。服务器。查询运行时没有语法错误,但问题是结果为空。我还在学习SQL,所以我很难搞清楚这个问题。
select *, volume/ case when National_Avg=0 then 1 else National_Avg end as FPD_Renewals
from (
select convert(decimal(10,0), COUNT(srf_borrower)*1.8) as Volume, year(datecompleted) as cal_year, month(datecompleted) as cal_month
from database1.dbo.datafile
where month(datecompleted) = month(dateadd(month,-1,current_timestamp))
and year(datecompleted) = year(dateadd(month,-1,current_timestamp))
group by month(datecompleted), year(datecompleted))a
join(select cal_date, National_Avg
from database1.dbo.calendar
where cal_date = month(dateadd(month,-1,current_timestamp))
AND cal_date = year(dateadd(month,-1,current_timestamp)))b
on a.cal_year = b.cal_date and a.cal_month = b.cal_date
我希望查询显示上个月的结果,因此当表1中的年份和月份与表2中的年份匹配时,表1中的数据类型为' datetime'表2中的数据类型是' datetime'同样。在我的日历表中,我有几个列,我有两个选项是' year'和'月'列,但这些数据类型不是' datetime'和sql给我一个转换错误。
表2中的一些示例数据:
Table 1
ID cal_month cal_year cal_date fy_date Tor Mtl National_avg
1 January 2018 2018-01-01 2018-01-01 22 22 22
我做错了什么,我该如何解决? 谢谢大家
答案 0 :(得分:1)
我认为第二个子查询只需要抽出月份和年份,这样你就可以比较苹果和苹果。
SELECT
*,
volume / CASE
WHEN National_Avg = 0 THEN 1
ELSE National_Avg
END AS FPD_Renewals
FROM (SELECT
CONVERT(decimal(10, 0), COUNT(srf_borrower) * 1.8) AS Volume,
YEAR(datecompleted) AS cal_year,
MONTH(datecompleted) AS cal_month
FROM database1.dbo.datafile
WHERE MONTH(datecompleted) = MONTH(DATEADD(MONTH, -1, current_timestamp))
AND YEAR(datecompleted) = YEAR(DATEADD(MONTH, -1, current_timestamp))
GROUP BY MONTH(datecompleted),
YEAR(datecompleted)) a
JOIN (SELECT
cal_date,
National_Avg,
YEAR(cal_date) AS cal_year,
MONTH(cal_date) AS cal_month
FROM database1.dbo.calendar
WHERE MONTH(cal_date) = MONTH(DATEADD(MONTH, -1, current_timestamp))
AND YEAR(cal_date) = YEAR(DATEADD(MONTH, -1, current_timestamp))) b
ON a.cal_year = b.cal_year
AND a.cal_month = b.cal_month