Site Sponsored By: SQLDSC - SQL Server Desired State Configuration
Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
Hi all,I have a table with three columns.BENTIDSomething_elseBEN contains a list of names (beneficiaries).TID contains a list of transaction IDs. Each beneficiary should have just ONE transaction ID. I need to see all the records (including the Something_else column) where a BEN has more than one TID.If a particular BEN only has one TID then those records should not appear.I've started with:SELECT DISTINCT(BEN+TID)FROM mytablebut the problem is that this includes all the BEN/TID pairings - I only want to see the records where there's more than one TID for a BEN.Many thanks in advance for any ideas!
webfred
Master Smack Fu Yak Hacker
8781 Posts
Posted - 2012-06-12 : 06:29:51
select * from table where BEN in (select BEN from table group by BEN,TID having count(*) > 1)No, you're never too old to Yak'n'Roll if you're too young to die.
sunitabeck
Master Smack Fu Yak Hacker
5155 Posts
Posted - 2012-06-12 : 06:33:20
Query it like this:
SELECT BEN, TID FROM myTable GROUP BY BEN, TID HAVING COUNT(*) > 1;
If you also want to see the Soemthing_else column, enhance it a bit like this:
SELECT a.* FROM myTable aINNER JOIN ( SELECT BEN, TID FROM myTable GROUP BY BEN, TID HAVING COUNT(*) > 1) b ON a.BEN = b.BEN AND a.TID = b.TID;
tom.mckay
Starting Member
4 Posts
Posted - 2012-06-12 : 06:36:38
Thanks, but this returns exactly the same number of records as I started with, i.e. it still returns the records where the BEN has only one TID.Here is some sample data:BEN/TID/Something_elseDave/1/Test1Dave/1/Test2Dave/1/Test3Tom/9/Test13Tom/9/Test14Tom/8/Test15Steve/3/Test99Steve/3/Test98Steve/3/Test97Pete/5/Test23Pete/5/Test69Pete/6/Test73In this case I'd need to see 6 records - i.e. all the records for Tom and Pete, as they have >1 TID associated with them. Dave and Steve should be filtered out because they each only have one TID.
webfred
Master Smack Fu Yak Hacker
8781 Posts
Posted - 2012-06-12 : 06:42:57
select * from table t1 where exists(select * from table t2 where t2.BEN=t1.BEN and t2.TID<>t1.TID)No, you're never too old to Yak'n'Roll if you're too young to die.
tom.mckay
Starting Member
4 Posts
Posted - 2012-06-12 : 06:43:22
I'd also need to see the Something_else column too for those six records.Thanks again
webfred
Master Smack Fu Yak Hacker
8781 Posts
Posted - 2012-06-12 : 06:43:54
yesNo, you're never too old to Yak'n'Roll if you're too young to die.
tom.mckay
Starting Member
4 Posts
Posted - 2012-06-12 : 06:45:27
It works!Thank you :)
webfred
Master Smack Fu Yak Hacker
8781 Posts
Posted - 2012-06-12 : 06:47:10
No, you're never too old to Yak'n'Roll if you're too young to die.