T-SQL:“压缩”具有相等值的行为1

时间:2012-07-16 13:10:35

标签: sql sql-server tsql

如果有任何行具有相同的值,是否有可能只显示一行?

我有以下情况:

  

ID | A列| B栏| C栏

     

1 | 2 | '测试'| 5

     

2 | 3 | “测试” | 6

     

3 | 2 | “测试” | 5

在这种情况下,我只想显示以下结果集:

  

ID | A列| B栏| C栏

     

1 | 2 | '测试'| 5

     

2 | 3 | “测试” | 6

感谢您的帮助。

问候,亲

4 个答案:

答案 0 :(得分:6)

由于id列,您的行不是完全重复的。如果你不关心id的哪个值出现,你可以做你想做的事情:

select max(id) as id, ColumnA, ColumnB, ColumnC
from t
group by ColumnA, ColumnB, ColumnC

如果你根本不需要id,这更简单:

select distinct ColumnA, ColumnB, ColumnC
from t

答案 1 :(得分:2)

Try this :

With cte As
( Select  * , row_number() over (partition by ColumnA, ColumnB,ColumnC
 order by ID ) as myrownumber from myTable
)
Select * from cte where myrownumber=1

答案 2 :(得分:0)

select id, column1,column2,colum3 from
(
    select *, row_number() over (partition by column1,column2,colum3 order by id) as sno 
    from table
) as t
where sno=1

答案 3 :(得分:0)

CREATE TABLE #test
(
    ID      TINYINT     NOT NULL,
    colA    TINYINT     NOT NULL,
    colB    VARCHAR(10) NOT NULL,
    colC    TINYINT     NOT NULL
);

INSERT INTO #test VALUES (1,2, 'test', 5);
INSERT INTO #test VALUES (2,3, 'test', 6);
INSERT INTO #test VALUES (3,2, 'test', 5);

SELECT 
    ID,
    ColA,
    ColB,
    ColC
FROM 
(   
    SELECT 
        ID,
        ColA,
        ColB,
        ColC,
        ROW_NUMBER() OVER(PARTITION BY ColA ORDER BY ColA DESC) AS RowNum
      FROM #test
) AS WorkTable
WHERE RowNum = 1