我正在尝试计算SQL查询中的日期,即date_required添加despatchdate中的天数 - 我目前收到错误无效列名'despatchdays'。如果despatchdays为null或“”,那么我希望它默认为-14。
SELECT order_no, order_line_no, currency, product, address1,description, date_required,
(SELECT despatchdays
FROM scheme.PDBtblSuppliers
WHERE SupplierIDFK = dbo.qryArrears2.supplier) AS despatchdays,
DATEADD(d, despatchdays, date_required) AS despatchdate
FROM dbo.qryArrears2
如何对其进行优化以使其正常工作?
我正在使用SQL 2000。
答案 0 :(得分:1)
你不能只是JOIN
表,然后像这样使用它:
SELECT
order_no,
order_line_no,
currency,
product,
address1,
description,
date_required,
despatchdays,
DATEADD(d, despatchdays, date_required) AS despatchdate
FROM
dbo.qryArrears2
JOIN scheme.PDBtblSuppliers
ON SupplierIDFK = dbo.qryArrears2.supplier
<强>更新强>
您可以将date_required
投射到这样的datetime
:
CAST(date_required AS DATETIME)
答案 1 :(得分:1)
You can use:
SELECT order_no
, order_line_no
, currency
, product
, address1
,description
, date_required
, DATEADD(day, coalesce(pd.despatchdays, -14), date_required) AS despatchdate
FROM dbo.qryArrears2 qa
INNER JOIN scheme.PDBtblSuppliers pd On pd.SupplierIDFK = qa.supplier
But it may give you more rows if there are several rows in PDBtblSuppliers for a supplier in qryArrears2.
You can also move despatchdate query inside the DATEADD:
SELECT * FROM (
SELECT order_no
, order_line_no
, currency
, product
, address1
, description
, date_required
, DATEADD(day
, coalesce((SELECT despatchdays FROM scheme.PDBtblSuppliers WHERE SupplierIDFK = qa.supplier), -14)
, date_required
) AS despatchdate
FROM dbo.qryArrears2 qa
) as d
WHERE despatchdate = '20150101'
coalesce(despatchdays, -14)
will replace despatchdays
by -14
if despatchdays
is NULL.
If date_required
is a (var)char, you should replace it by a date in your table or cast is to data(time): CAST(date_required as date)