我在SQL Server中编写查询以显示上周收到的所有作业,该查询将成为Crystal Report中自动报告的基础,语法如下
SELECT TOP (100) PERCENT
DATENAME(yy, dbo.JOB.JOB_TAKEN_DATE) + '-' + DATENAME(wk, DATEADD(wk, - 1, dbo.JOB.JOB_TAKEN_DATE)) AS PERIOD,
dbo.JOB.CUST_ORD_NO AS [ORDER NO],
dbo.JOB.JOB_TAKEN_DATE AS RECEIVED,
dbo.JOB.JOB_COMPLETION_DATE AS COMPLETED,
UPPER(ISNULL(dbo.JOB.PROPERTY_LOCATION, ' ') + ' ' + dbo.JOB.PROPERTY_NAME + ' ' + REPLACE(REPLACE(REPLACE(dbo.JOB.PROPERTY_ADDRESS, CHAR(10), ' '), CHAR(13), ' '), CHAR(9), ' ') + ' ' + dbo.JOB.PROPERTY_POSTCODE) AS ADDRESS,
REPLACE(REPLACE(REPLACE(dbo.JOB.WORKS_TO_BE_CARRIED_OUT, CHAR(10), ' '), CHAR(13), ' '), CHAR(9), ' ') AS [WORKS ORDERED],
dbo.JOB.JOB_TARGET_DATE,
dbo.['TMO properties$'].F2
FROM
dbo.JOB
INNER JOIN
dbo.CUSTOMERPROPERTY ON dbo.JOB.CUSTOMER_PROPERTY_ID = dbo.CUSTOMERPROPERTY.CUSTOMER_PROPERTY_ID
INNER JOIN
dbo.['TMO properties$'] ON dbo.CUSTOMERPROPERTY.EXTERNAL_REFERENCE = dbo.['TMO properties$'].F1
WHERE
DATENAME(yy, dbo.JOB.JOB_TAKEN_DATE) + '-' + DATENAME(wk, DATEADD(wk, - 1, dbo.JOB.JOB_TAKEN_DATE)) = DATENAME(yy, CURRENT_TIMESTAMP) + '-' + DATENAME(wk, DATEADD(wk, - 1, CURRENT_TIMESTAMP))
ORDER BY
RECEIVED
运行查询时出现错误
在日期'中添加值列导致溢出
谁能看到我做错了什么?
答案 0 :(得分:0)
您提供的代码中唯一可能出现错误的地方是:dateadd(week, -1, j.job_taken_date)
,select
和where
中都会显示错误。
您可以使用datepart()
获取week
整数并将其减少1而不是使用date
调整convert(varchar(2),datepart(week,j.job_taken_date)-1)
值来解决此问题。
看起来你的where
条款意味着"本周采取的工作"。如果是这种情况,您可以简化where
以比较截断到一周的日期,而不是现在正在构建的字符串比较,这可能会导致您的错误。
您还可以使用表别名使查询更容易阅读,而不是使用日期/时间操作的简写。
select top (100) percent
datename(year, j.job_taken_date)
+ '-'
--+ datename(week, dateadd(week, -1, j.job_taken_date)
+ convert(varchar(2),datepart(week,j.job_taken_date)-1)
) as period
, j.cust_ord_no as [order no]
, j.job_taken_date as received
, j.job_completion_date as completed
, upper(isnull(j.property_location, ' ')
+ ' ' + j.property_name + ' '
+ replace(replace(replace(j.property_address, char(10), ' '), char(13), ' '), char(9), ' ')
+ ' ' + j.property_postcode
) as address
, replace(replace(replace(j.works_to_be_carried_out, char(10), ' '), char(13), ' '), char(9), ' '
) as [works ordered]
, j.job_target_date
, tmop.F2
from dbo.job j
inner join dbo.customerproperty cp
on j.customer_property_id = cp.customer_property_id
inner join dbo.['tmo properties$'] tmop
on cp.external_reference = tmop.F1
where dateadd(week, datediff(week, 0, j.job_taken_date), 0)
= dateadd(week, datediff(week, 0, current_timestamp), 0)
order by received