【问题标题】:Row Number for a view where the number is not affected by the where clause视图的行号,其中数字不受 where 子句影响
【发布时间】:2013-03-10 20:16:30
【问题描述】:

SQL Server 2008

我有一个包含许多行的视图,其中也可以多次获得确切的行。我已经尝试将 ROW_NUMBER() OVER ( ORDER BY col1 ) 作为 row_id 但遇到了问题:

当使用 JOIN 或 WHERE 子句时,row_ids 会动态调整到新的结果集。我需要的是 row_id 来表示在视图中为该行提供的 row_id 值,而无需任何 JOIN 或 WHERE 子句。

有什么想法吗?

编辑:我添加了一个示例,应该在发布之前完成。

没有 WHERE 子句:

SELECT ROW_NUMBER() OVER (ORDER BY col1) as row_id, result.*
来自
(

SELECT 'Adam' col1, 'West' col2
联合所有
选择“亚当”col1、“科尔”col2
联合所有
选择'亚当' col1,'西' col2
联合所有
SELECT 'Danny' col1, 'West' col2

) 结果

结果:

row_id  col1    col2
1       Adam    Cole
2       Adam    West
3       Adam    West
4       Danny   West

现在当我使用 WHERE 子句时

SELECT ROW_NUMBER() OVER (ORDER BY col1) as row_id, result.*
来自
(

SELECT 'Adam' col1, 'West' col2
联合所有
选择“亚当”col1、“科尔”col2
联合所有
选择'亚当' col1,'西' col2
联合所有
SELECT 'Danny' col1, 'West' col2

) 结果
WHERE col2='West'

结果:

row_id  col1    col2
1       Adam    West
2       Adam    West
3       Danny   West

想要的结果:

row_id  col1    col2
2       Adam    West
3       Adam    West
4       Danny   West

【问题讨论】:

  • 请发布您的表结构、一些示例数据和所需的结果。

标签: sql sql-server view


【解决方案1】:

您可以在子查询中生成行号。这些不受外部查询中的joinwhere 子句的影响:

select  *
from    (
        select  row_number() over order by col1) as rn
        ,       *
        from    YourTable
        ) as YourTableWithRowNumber
join    OtherTable
on      YourTableWithRowNumber.id = OtherTable.YourTableId
where   YourTableWithRowNumber.col1 not like '%excludeme%'

【讨论】:

  • 这真的可以 - 我会试一试,谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多