简体   繁体   中英

Need a SQL statement to filter rows

There is a table which look like this:
在此输入图像描述

I need to retrieve only highlighted records. And I need a query which should work on bigger table where are millions of records are exists.

Criteria:
There are 4 sets, 1st and 3rd have the similar values but 2nd and 4th sets have different values

Edit:
I made slight modification in the table( ID column added). How can we achieve the same with the ID column?

在此输入图像描述

return only this kind of set where 1 or more different value exists in the set

create table #ab
(
col1a int,
colb char(2)
)

insert into #ab
values
(1,'a'),
(1,'a'),
(1,'a'),
(2,'b'),
(2,'c'),
(2,'c')

select id,col1a,colb
from #ab
where col1a in (
Select col1a from #ab group by col1a having count (distinct colb)>1)

Regarding the performance over millions of rows,i would probably check the execution plan and deal with it.with my sample data set and my query ,Distinct sort takes nearly 40% of cost..with millions of rows,it can probably go to tempdb as well..so i suggest below index which can eliminate more rows

create index nci on #ab(colb)
include(col1a)

You can also achieve it using INNER JOIN instead of IN as it is million rows query.

SELECT f.colA,f.colB
FROM
filtertable f
INNER JOIN
(
SELECT colA
FROM filtertable
GROUP BY colA
HAVING COUNT(DISTINCT colB)>1
) f1
ON f.colA = f1.colA

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM