我在sql server 2012中使用新的Lead olap函数时遇到问题。

CREATE TABLE Atext (id int, bez varchar(10), von date);

GO

INSERT INTO Atext VALUES (1, 't1', '2001-01-01'), (1, 't2', '2012-01-01'), (2, 'a1', '2020-01-01'), (2,'a1' , '2030-01-01'), (2, 'b', '2040-05-01'), (2, 'a3', '2989-05-01');
GO

SELECT
        id,
        bez,
        von,
        lead(von,1,0) over (partition by id ORDER BY von) -1 as bis
FROM
        Atext
order by
        id,
        Von

选择查询将引发错误:
Msg 206, Level 16, State 2, Line 1
Operand type clash: int is incompatible with date

为什么在数据类型日期时间方面有限制?

我知道一种解决方法,但这不是很好:
SELECT
    id,
    bez,
    CAST(vonChar AS DATE) AS Von,
    CASE
        WHEN bisChar <> '0'
        THEN (DATEADD(DAY,-1,(CAST((
                    CASE
                        WHEN bisChar <> '0'
                        THEN vonChar
                        ELSE NULL
                    END)AS DATE)) ))
        ELSE NULL /*'9999-12-31'*/
    END AS Bis
FROM
    (
        SELECT
            id,
            bez,
            vonChar ,
            lead(vonChar,1,0) over (partition BY id ORDER BY vonChar) AS bisChar
        FROM
            (
                SELECT
                    id,
                    bez,
                    CAST(von AS VARCHAR(10)) vonChar
                FROM
                    Atext) tab ) tab2
ORDER BY
    id,
    Von

Microsoft SQL Server 2012(SP1)-11.0.3128.0(X64)

最佳答案

您可以在此查询中使用DATEADD()。同样,LEAD数据类型的默认值不能是0,因此我将其更改为NULL,或者可以使用任何DATE常量。

SELECT
        id,
        bez,
        von,
        DATEADD(DAY,-1,lead(von,1,NULL)
                       over (partition by id ORDER BY von)) as bis
FROM
        Atext
order by
        id,
        Von

SQLFiddle demo

关于sql - SQL Server Lead-日期问题,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23888823/

10-10 15:03