2015-11-12 121 views
0

我想計算一個SQL查詢中的日期,它是date_required添加despatchdate中的天數 - 我目前收到錯誤無效的列名稱'despatchdays'。如果despatchdays爲空或「」,那麼我希望它默認爲-14。在SQL查詢中計算日期

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

回答

1

您可以使用:

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 

但它可以給你更多的行是否有PDBtblSuppliers幾排在qryArrears2供應商。

您還可以移動despatchdate查詢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)-14如果despatchdays爲NULL替換despatchdays

如果date_required是(VAR)字符,你應該在你的餐桌或鑄造日期替換它是將數據(時間):CAST(date_required如日期)

+0

AS附近的語法不正確? – Emma

+1

我刪除了AS despatchdays,因爲它不再需要查詢2 –

+0

非常感謝 - 現在只有這樣,如果PDBtblSuppliers表中沒有匹配,它會空白 - 如果它的eof可以默認爲-14? – Emma

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到a datetime是這樣的:

CAST(date_required AS DATETIME) 
+0

感謝阿里昂,只是想它現在 - 字段date_required不是一個日期字段,我怎麼能CAST它作爲一個? – Emma

+1

@Emma:更新了答案 – Arion