Database, Programming, SQL, SQL Server 2000, SQL Server 2005, SQL Server 2008, SQL Server 2012, SQL Tips, Transact-SQL, tSQL

T-SQL Simple Example of Finding Records with More than One Entry

Here is a super-simple example of using a T-SQL query to find records that have more than one table entry.

In this example we’ll populate a temporary table with entries of pets at a pet shop. Then we’ll run a query to check for what kind of pets are at the pet shop in a quantity greater than one.

As you can see from how we populated the table we expect to see the result that the only kind of pet with more than one individual is the type ‘Puppies’

To accomplish this, we do a simple GROUP BY the Pet Type and then filter using: HAVING COUNT of PetType greater than one. Presto, mission accomplished!

DECLARE @TestTable TABLE( Id INT IDENTITY(1,1) NOT NULL, [PetsName] [varchar](100) NULL, [PetType] [varchar](100) NULL )
INSERT INTO @TestTable ([PetsName],[PetType]) VALUES ('Fido','Puppy')
INSERT INTO @TestTable ([PetsName],[PetType]) VALUES ('Isa','Iguana')
INSERT INTO @TestTable ([PetsName],[PetType]) VALUES ('Mittens','Kitten')
INSERT INTO @TestTable ([PetsName],[PetType]) VALUES ('Spot','Puppy')
SELECT [PetType]
FROM @TestTable
GROUP BY [PetType]
HAVING COUNT([PetType])>1
Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s