如何忽略SQL Server中的列

时间:2018-07-12 16:24:27

标签: sql sql-server sql-server-2008

我有这个查询:

Select * 
from 
    (Select 
         * 
         ROW_NUMBER() OVER (PARTITION BY TID ORDER BY TID) AS RowNumber 
     from 
         MyTable 
     where 
         Eid = 'C1') as a 
where 
    a.RowNumber = 1

并显示以下结果:

Column1  Column2    RowNumber  
------------------------------
 Value1   value2         1

我想忽略select语句中的RowNumber列,并且我不想列出select查询中的所有列(100列以上只是一个示例)。

如何在SQL Server中执行此操作?

3 个答案:

答案 0 :(得分:3)

好吧,如果您使用子查询和select来获得唯一行,则必须列出外部row_number()中的所有列。

另一种方法使用相关的子查询,但是需要在表中具有一些唯一的列。如果您有一个:

select t.*
from mytable t
where t.col = (select max(t2.col) from mytable t2 where t2.tid = t.tid and t2.eid = 'C1');

使用正确的索引,它可以比row_number()版本的性能更好。

如果您没有唯一的列,则可以执行以下操作:

select t.*
from (select distinct tid from mytable where eid = 'C1') tc cross apply
     (select top 1 t.*
      from mytable t
      where t.tid = tc.tid and t.eid = 'C1'
     ) t;

答案 1 :(得分:2)

将查询包装为子查询,并从中选择特定列,如下所示:

SELECT x.Column1, x.Column2
FROM
(
    Select * from (Select * ROW_NUMBER() OVER (PARTITION BY TID ORDER BY TID) 
    AS RowNumber from MyTable where Eid="C1") as a where a.RowNumber=1
) AS x

或将原始“选择”更改为:

    Select a.[Column1], a.[Column2] 
    from 
    (
      Select * ROW_NUMBER() OVER (PARTITION BY TID ORDER BY TID) 
      AS RowNumber from MyTable where Eid="C1"
    ) as a 
    Where a.RowNumber=1

答案 2 :(得分:2)

从查询中替换*,以明确说明您希望的列

select x.Column1, x.Column2 FROM (
    Select * from (Select * ROW_NUMBER() OVER (PARTITION BY TID ORDER BY TID) 
    AS RowNumber from MyTable where Eid="C1") as a where a.RowNumber=1) AS x