通过cte的结果找到今天的日期和日期之间的日期差异。在sql表中给出日期......不工作?

时间:2016-03-03 10:58:53

标签: sql sql-server sql-server-2012

WITH cte AS 
(
    SELECT 
        SUBSTRING(Availability, PATINDEX('% [0-9][0-9]-[0-9][0-9]-[0-9][0-9][0-9][0-9]%', 
        [Availability]), 11) AS [Date Part]
    FROM 
        [ScrappedData_Regina]
)
-- extracts date part from a column
SELECT DISTINCT 
    [Product Name],
    [SKU],
    DATEDIFF(DAY, CAST(cte AS DATE), CAST(GETDATE() AS DATE)) AS [Delivery Date]
FROM
    ScrappedData_Regina
-- gives date difference between todays date & given date in sql table

1 个答案:

答案 0 :(得分:0)

您不能使用cte,就好像它是单个值一样。 cte是一张桌子。 我想你想要这样的东西:

SELECT DISTINCT [Product Name],
                [SKU],
                DATEDIFF(DAY, 
                      CAST(
                          SUBSTRING(
                              Availability, 
                              PATINDEX('% [0-9][0-9]-[0-9][0-9]-[0-9][0-9][0-9][0-9]%', 
                                  [Availability]), 
                            11) 
                       AS DATE), 
                     CAST(GETDATE() AS DATE)) AS [Delivery Date]
FROM ScrappedData_Regina
-- gives date difference between todays date & given date in sql table

或者,如果您坚持使用cte,则还必须在其中包含表的行标识符,以便您可以将其与join一起使用:

WITH cte AS (
    SELECT Id, SUBSTRING(Availability, PATINDEX('% [0-9][0-9]-[0-9][0-9]-[0-9][0-9][0-9][0-9]%', [Availability]), 11) AS 
    FROM [ScrappedData_Regina]
)
-- extracts date part from a column
SELECT DISTINCT [Product Name],
                [SKU],
                DATEDIFF(DAY, CAST([Date Part]AS DATE), CAST(GETDATE() AS DATE)) AS [Delivery Date]
FROM ScrappedData_Regina t
INNER JOIN cte ON(t.Id = cte.Id)
-- gives date difference between todays date & given date in sql table