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.
| Author |
Topic |
|
jung1975
Aged Yak Warrior
503 Posts |
Posted - 2005-01-20 : 14:37:14
|
I have a table looks like:Members Categoty_IDA 1B 1C 1D 1A 2C 2D 2D 3 I would like to generate a output that shows the count of members break down by the number of Category ID which they have..For example, Category CountMembers with one category ID 1 *only B has only one Members with 2 category ID 2 **A and C has 2 category IDMembers with 3+ category ID 1 ***only D has 3+ category ID How can I do this? |
|
|
isanlu
Starting Member
7 Posts |
Posted - 2005-01-20 : 15:13:08
|
| --THIS IS HARD TO EXPLAIN BUT IT WORK USING YOUR EXAMPLE OF A,B,C,D--CREATE A TABLE AND INSERT THE VALUES HERE--YOU CAN POPULATE FROM YOUR SOURCE TABLECREATE TABLE #TEMP1 (Member char(1),CategoryID int)INSERT INTO #TEMP1 (Member,CategoryID)VALUES ( 'A',1)INSERT INTO #TEMP1 (Member,CategoryID)VALUES ( 'B',1)INSERT INTO #TEMP1 (Member,CategoryID)VALUES ( 'C',1)INSERT INTO #TEMP1 (Member,CategoryID)VALUES ( 'D',1)INSERT INTO #TEMP1 (Member,CategoryID)VALUES ( 'A',2)INSERT INTO #TEMP1 (Member,CategoryID)VALUES ( 'C',2)INSERT INTO #TEMP1 (Member,CategoryID)VALUES ( 'D',2)INSERT INTO #TEMP1 (Member,CategoryID)VALUES ( 'D',3)--FIND OUT HOW MANY CATEGORIES EACH MEMBER BELONGS TO AND PUT THAT INTO #TEMP2SELECT Member, Count(*) As CategoriesForMemberINTO #TEMP2 FROM #TEMP1 GROUP by Member--GROUP BY THE NUMBER OF MEMBERS IN A CATEGORY AND CHANGE THE--FIELD NAME TO RETURN THE ANSWERSELECT 'Members with '+Convert(Char(1),CategoriesForMember)+' categoryID', Count(*) As NumberOfMembers FROM #TEMP2 GROUP BY CategoriesForMemberTRY RUNNING THIS SCRIPT FIRST TO SEE IF IT MAKES SENSE. |
 |
|
|
Bustaz Kool
Master Smack Fu Yak Hacker
1834 Posts |
Posted - 2005-01-20 : 16:10:12
|
| select MemberCount, Count(MemberCount)from ( -- Generates a list of Members and their count select Member, count(*) MemberCount from dbo.Junk group by Member ) t join ( -- List of numbers 1,2 and 3 select 1 Number union all select 2 union all select 3 ) n123 on (n123.Number in (1, 2) and n123.Number = t.MemberCount) or (n123.Number = 3 and t.MemberCount >= 3)group by MemberCountorder by MemberCountHTH=================================================================Scriptures, n. The sacred books of our holy religion, as distinguished from the false and profane writings on which all other faiths are based.-Ambrose Bierce, writer (1842-1914) [The Devil's Dictionary] |
 |
|
|
|
|
|
|
|