SQL Server Forums
Profile | Register | Active Topics | Members | Search | Forum FAQ
 
Register Now and get your question answered!
Username:
Password:
Save Password
Forgot your Password?

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 query
 New Topic  Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

gagani
Yak Posting Veteran

88 Posts

Posted - 05/24/2012 :  18:31:01  Show Profile  Reply with Quote
for the table,

orderid name workid
100 A 1001
100 A 1002
101 A 1003
101 B 1004
101 A 1005
101 B 1006

I want the output which has got more than one entry of same orderid with same name
In the above case, the output should be 100. 101 has more than one entry of orderid with same name but it has also got another entry with different name.
output should only be 100

tkizer
Almighty SQL Goddess

USA
35017 Posts

Posted - 05/24/2012 :  18:46:29  Show Profile  Visit tkizer's Homepage  Reply with Quote
Here's what I came up with:


create table #t (orderid int, name char(1), workid int)
insert into #t values(100,'A', 1001)
insert into #t values(100,'A', 1002)
insert into #t values(101,'A', 1003)
insert into #t values(101,'B', 1004)
insert into #t values(101,'A', 1005)
insert into #t values(101,'B', 1006)

select orderid, count(*) as NameCount
from
(
	select orderid, name
	from #t
	group by orderid, name
	having count(*) > 1
) t
group by orderid
having count(*) = 1

drop table #t


Tara Kizer
Microsoft MVP for Windows Server System - SQL Server
http://weblogs.sqlteam.com/tarad/

Subscribe to my blog

Edited by - tkizer on 05/24/2012 18:47:21
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

India
48076 Posts

Posted - 05/25/2012 :  09:59:38  Show Profile  Reply with Quote

select t.*
from #t t
inner join
(
select orderid
from #t
group by orderid
having count(distinct name)=1
and count(*) > 1
)t1
on t1.orderid = t.orderid


------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page

tkizer
Almighty SQL Goddess

USA
35017 Posts

Posted - 05/25/2012 :  12:24:47  Show Profile  Visit tkizer's Homepage  Reply with Quote
quote:
Originally posted by visakh16


select t.*
from #t t
inner join
(
select orderid
from #t
group by orderid
having count(distinct name)=1
and count(*) > 1
)t1
on t1.orderid = t.orderid





I didn't look at the execution plan, but wouldn't yours be less efficient since it's hitting the table twice?

Tara Kizer
Microsoft MVP for Windows Server System - SQL Server
http://weblogs.sqlteam.com/tarad/

Subscribe to my blog
Go to Top of Page
  Previous Topic Topic Next Topic  
 New Topic  Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.12 seconds. Powered By: Snitz Forums 2000