如何过滤 ROW_NUMBER()

How to filter on ROW_NUMBER()

我正在尝试 select 将 NAME 与数据集以及 return 其他列区分开来。我已经在一定程度上发挥了作用,但就是不知道如何将它们组合在一起。

我怀疑我需要一个 WITH x( 或其他但不确定

这是代码及其 return 数据的图像。从这里我只想展示 WHERE RN=1 图中红圈所示

Select
    row_number() over (partition by tagname order by adddate) as RN,
    tagname,
    RIGHT(v_AlarmsWithTagname.TagName,charindex('.',REVERSE(v_AlarmsWithTagname.TagName))-1) as SCADA_tag, 
    convert(varchar(12) , adddate , 101) as AddDate,
    left(tagname,CHARINDEX('.',tagname)-1) as 'Table',
    [CC_NOTE_LOG].dbo.SCADA_DB.groupid as 'Group',
    [CC_NOTE_LOG].dbo.SCADA_DB.dataset as 'Dataset', 
    [CC_NOTE_LOG].dbo.SCADA_DB.Description as 'Description'
FROM "Buckeye KB".dbo.v_AlarmsWithTagname
join 
    [CC_NOTE_LOG].dbo.SCADA_DB
on 
    RIGHT(v_AlarmsWithTagname.TagName,charindex('.',REVERSE(v_AlarmsWithTagname.TagName))-1)=[CC_NOTE_LOG].dbo.SCADA_DB.SCADA_SR_TAG
where
    [CC_NOTE_LOG].dbo.SCADA_DB.groupid<>'test' and
    [CC_NOTE_LOG].dbo.SCADA_DB.groupid not like 'Keep%' and
    [CC_NOTE_LOG].dbo.SCADA_DB.groupid not like 'delete%' and
    Tagname not like '%.ES_%' and
    Tagname not like '%.OPC_%'

你只需要一个common table expression (CTE)。为此,您使用以下语法:;with CTE AS (query) SELECT whatever FROM CTE ...请查看下面的代码块。

;with CTE AS (
Select
    row_number() over (partition by tagname order by adddate) as RN,
    tagname,
    RIGHT(v_AlarmsWithTagname.TagName,charindex('.',REVERSE(v_AlarmsWithTagname.TagName))-1) as SCADA_tag, 
    convert(varchar(12) , adddate , 101) as AddDate,
    left(tagname,CHARINDEX('.',tagname)-1) as 'Table',
    [CC_NOTE_LOG].dbo.SCADA_DB.groupid as 'Group',
    [CC_NOTE_LOG].dbo.SCADA_DB.dataset as 'Dataset', 
    [CC_NOTE_LOG].dbo.SCADA_DB.Description as 'Description'
FROM "Buckeye KB".dbo.v_AlarmsWithTagname
join 
    [CC_NOTE_LOG].dbo.SCADA_DB
on 
    RIGHT(v_AlarmsWithTagname.TagName,charindex('.',REVERSE(v_AlarmsWithTagname.TagName))-1)=[CC_NOTE_LOG].dbo.SCADA_DB.SCADA_SR_TAG
where
    [CC_NOTE_LOG].dbo.SCADA_DB.groupid<>'test' and
    [CC_NOTE_LOG].dbo.SCADA_DB.groupid not like 'Keep%' and
    [CC_NOTE_LOG].dbo.SCADA_DB.groupid not like 'delete%' and
    Tagname not like '%.ES_%' and
    Tagname not like '%.OPC_%'
)
SELECT * FROM CTE WHERE [RN] = 1

同样重要的是要注意,CTE 不必直接跟在 SELECT 之后。请参阅以下 link 了解 CTE 指南:https://msdn.microsoft.com/en-us/library/ms175972.aspx