如何通过删除SQL中的重复行来创建新表?

时间:2019-04-09 08:54:22

标签: sql sql-server

我有一个看起来像这样的桌子

ID A B C 
1  1 0 0
1  1 0 0
2  1 1 0
2  1 1 0

如何在SQL中删除重复的行,以便剩下一个看起来像这样的表:

ID A B C 
1  1 0 0
2  1 1 0

2 个答案:

答案 0 :(得分:1)

使用row_number()

with cte as
(
select *, row_number() over(partition by id order by id) as rn
from tablename
)

delete from cte where rn<>1

答案 1 :(得分:1)

df= df.pivot_table(index=['id','id_2'], columns=['col_1', 'col_2'], values='value')

print (df.columns)
MultiIndex(levels=[['A', 'B'], ['X', 'Z']],
           codes=[[0, 0, 1, 1], [0, 1, 0, 1]],
           names=['col_1', 'col_2'])

df.columns = df.columns.map('_'.join)
df = df.reset_index()
print (df)

   id  id_2   A_X   A_Z   B_X   B_Z
0   1     6  10.0   NaN   NaN   NaN
1   2     5   NaN  20.0   NaN   NaN
2   3     4  30.0   NaN   NaN   NaN
3   4     3   NaN   NaN   NaN  40.0
4   5     2   NaN   NaN  50.0   NaN
5   6     1   NaN   NaN   NaN  60.0

这是最简单的方法。