假设我有一个SQL Server表,其中包含许多列:
Col1: Col2: Col3: ... Coln:
Val1_1 Val1_2 Val1_3 Val1_n
Val2_1 Val2_2 Val2_3 Val2_n
Val3_1 Val3_2 Val3_3 Val3_n
Val3_1 Val4_2 Val4_3 Val4_n
Val3_1 Val5_2 Val5_3 Val5_n
在这种情况下,Val3_1
会在最后3条记录中重复Col1
,而其余值不会重复。
如何编写查询以返回Col1
的值重复的完整列集,以便返回:
Col1: Col2: Col3: ... Coln:
Val3_1 Val3_2 Val3_3 Val3_n
Val3_1 Val4_2 Val4_3 Val4_n
Val3_1 Val5_2 Val5_3 Val5_n
我尝试使用Group By
函数,但我必须写出每个列的名称(这非常令人沮丧),我希望有类似的东西:
SELECT MyTable.* FROM MyTable WHERE count(MyTable.Col1) OVER() > 1
显然,这不起作用,但我怎么能沿着这些方向做点什么?
感谢!!!
答案 0 :(得分:4)
您可以使用子查询:
select *
from mytable t1
inner join
(
select count(col1) Total, col1
from mytable
group by col1
having count(col1) > 1
) t2
on t1.col1 = t2.col1
或者您可以使用count(*) over()
:
select *
from
(
select *,
count(*) over(partition by col1) tot
from mytable
) src
where tot > 1