我正在尝试从数据集中选择不同的NAME,但也返回其他列。我有它在某种程度上工作,但只是无法弄清楚如何把它结合在一起。
我怀疑我需要一个WITH x(或其他东西,但我不确定
这是CODE和它返回的数据的图像。从这里我只想表现出来
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_%'
答案 0 :(得分:7)
你只需要一个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
。有关CTE指南,请参阅以下链接:https://msdn.microsoft.com/en-us/library/ms175972.aspx