使用 SQL 查询标记错误的行

Marking the wrong row using an SQL query

我需要一个 SQL 查询的建议。我有 table:

SELECT [ID]
      ,[MATNR] as type
      ,[VLPLA] as whence
      ,[NLPLA] as whither
      ,[TIMESTAMP]
  FROM [DNMST].[dbo].[Visualization]


 ID        type      whence  whither    TIMESTAMP
9430945  1465C04080  TRANSFER  GH-001    2020-10-02 12:35:48.000
9479333  1465C04073  GH-001    GH-004    2020-10-02 14:05:51.000
9705379  1465C04080  TRANSFER  GH-001    2020-10-02 20:59:12.000
9705380  1465C04080  TRANSFER  GH-001    2020-10-02 20:59:22.000
9705658  1465C04080  TRANSFER  GH-002    2020-10-02 20:59:52.000
12411110 1465C04073  GH-004    GH-001    2020-10-06 07:35:51.000

而且我需要标记错误的行。 “whither”列指示只能放置一种类型的位置(“type”列)。代替 GH-001 的是第一个类型“4080”(根据“时间戳”),但随后在同一位置添加了类型“4073”。我需要将此行标记为错误。我在DENSE_RANK之前尝试过,然后创造条件,但是我做不到。 当我使用:

SELECT TOP (1000) [ID]
      ,RIGHT(MATNR,24) as type
      ,[VLPLA] as whence
      ,[NLPLA] as whither
      ,[TIMESTAMP]
      ,DENSE_RANK() over (partition by MATNR,NLPLA order by timestamp desc) as status
  FROM [DNMST].[dbo].[Visualization]

我两次获得 GH-001 的状态 1(“whither”列)这两个中只有一个是错误的(较新的那个)

例如我试过这个,但它也是错误的。

SELECT TOP (1000) [ID]
      ,RIGHT(MATNR,24) as type
      ,[VLPLA] as whence
      ,[NLPLA] as whither
      ,[TIMESTAMP]
      ,DENSE_RANK() over (partition by MATNR,NLPLA order by timestamp desc) as status,
      CASE WHEN  (DENSE_RANK() over (partition by MATNR,NLPLA order by timestamp desc) = 1  AND NLPLA=NLPLA THEN 'WRONG'
      ELSE 'Right'
      End AS status_text

  FROM [DNMST].[dbo].[Visualization]

如何正确查询sql? 谢谢

我认为此查询标识了 'whither' 的 'type' 与最早分配的 'type' 不同的行。

with whither_cte as (
    select *, row_number() over (partition by whither order by [timestamp] rn
    from [DNMST].[dbo].[Visualization])
select * 
from [DNMST].[dbo].[Visualization] v
     join whither_cte wc on v.whither=wc.whither
                            and v.ID<>wc.ID
                            and v.[type]<>wc.[type]
                            and wc.rn=1;

使用FIRST_VALUE()解析函数

CASE WHEN [TYPE] <> FIRST_VALUE([TYPE]) OVER (PARTITION BY whither ORDER BY timestamp)
     THEN 'WRONG' ELSE 'RIGHT' END

FIRST_VALUE()

SELECT *
    ,CASE 
        WHEN (
                FIRST_VALUE([type]) OVER (
                    PARTITION BY [whither] ORDER BY [TIMESTAMP]
                    )
                ) <> [type]
            THEN 'Bad'
        ELSE 'Good'
        END AS [Status]
FROM  [DNMST].[dbo].[Visualization]