以下是我的数据。
{{1}}
我无法获取具有相同数据且出现2次的ID。
根据以上数据,预期的id为1,2。其中2次参与重复。 请帮忙。
答案 0 :(得分:0)
select distinct id
from tbl x
join (select col1,
col2,
col3,
col4
from tbl
group by col1,
col2,
col3,
col4
having count(distinct id) > 1) y
on x.col1 = y.col1
and x.col2 = y.col2
and x.col3 = y.col3
and x.col4 = y.col4
小提琴: http://www.sqlfiddle.com/#!6/8bce9/3/0
您的评论似乎建议您希望所有行上的ID在第1,2,3和4列中具有相同的行,而不仅仅是某些行。但是,如果是这种情况,ID#1和2甚至不匹配。无论如何,如果这真的是你想要的 - 也许是,我不知道 - 这应该这样做。它不会返回上面的示例数据的结果,因为就像我说的那样,ID#1的第2行与ID#2的第2行不匹配。
select id
from tbl t
where exists (select 1
from tbl x
where x.col1 = t.col1
and x.col2 = t.col2
and x.col3 = t.col3
and x.col4 = t.col4
and x.id <> t.id
and not exists (select 1
from tbl z
where z.id = x.id
and z.col1 <> x.col1
or z.col2 <> x.col2
or z.col3 <> x.col3
or z.col4 <> x.col4));
答案 1 :(得分:0)
尝试以下sql
select ID from
(
select ID,Col1,Col2,Col3,Col4, count(*) from table
Group by ID,Col1,Col2,Col3,Col4
Having count(*) > 1
) as UniqueData
答案 2 :(得分:0)
一般想法
WITH
CTE_Groups
AS
(
SELECT DISTINCT ID
FROM tbl
)
,CTE_GroupsAggregated
AS
(
SELECT
CTE_Groups.ID
,CA_Data.XML_Value AS DataValues
FROM
CTE_Groups
CROSS APPLY
(
SELECT
CAST(Col1 AS varchar(10))+','+
CAST(Col2 AS varchar(10))+','+
CAST(Col3 AS varchar(10))+','+
CAST(Col4 AS varchar(10))+','
FROM tbl
WHERE tbl.ID = CTE_Groups.ID
ORDER BY Col1, Col2, Col3, Col4 FOR XML PATH(''), TYPE
) AS CA_XML(XML_Value)
CROSS APPLY
(
SELECT CA_XML.XML_Value.value('.', 'NVARCHAR(MAX)')
) AS CA_Data(XML_Value)
)
,CTE_Duplicates
AS
(
SELECT DataValues
FROM CTE_GroupsAggregated
GROUP BY DataValues
HAVING COUNT(*) > 1
)
SELECT
CTE_GroupsAggregated.ID
FROM
CTE_GroupsAggregated
INNER JOIN CTE_Duplicates ON CTE_Duplicates.DataValues = CTE_GroupsAggregated.DataValues
;
结果集
ID
1
2
更好地了解它的工作原理包括DataValues
到输出中并检查每个CTE的中间结果。