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.

 All Forums
 SQL Server 2008 Forums
 Transact-SQL (2008)
 group by containing different fields

Author  Topic 

haler
Starting Member

13 Posts

Posted - 2012-06-05 : 19:37:20
Hi

What I am trying to do is find all the _key_out which have a count of more than one, but they have to also have both source a and b within them,

Below is a sample where I can get all the _key_out with a count greater than one but I cant get it to show only the _key_out which contain both source a and b

Any help would be much appreciated, thanks.

  CREATE TABLE organisation
( _key_out int,
source nvarchar(50),
);

INSERT INTO organisation (_key_out, source)
VALUES
(1,'A'),
(1,'A'),
(1,'A'),
(2,'B'),
(2,'B'),
(3,'A'),
(4,'B'),
(4,'A'),
(5,'A'),
(6,'A'),
(6,'B'),
(7,'B'),
(8,'A'),
(8,'B'),
(8,'A'),
(9,'A'),
(10,'A'),
(10,'A');

SELECT _key_out, COUNT(*) FROM organisation
GROUP BY _key_out
HAVING COUNT(*) > 1

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2012-06-05 : 21:09:31
[code]
SELECT _key_out, COUNT(*) FROM organisation
GROUP BY _key_out
HAVING COUNT(DISTINCT source) > 1
[/code]

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

Go to Top of Page

haler
Starting Member

13 Posts

Posted - 2012-06-05 : 21:31:46
Thanks Visakh it worked perfectly, can't believe I didn’t see that.
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2012-06-05 : 21:51:38
no probs..it happens to all
you're welcome

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

Go to Top of Page
   

- Advertisement -