Solved

# Special grouped select in a SQL table

Posted on 2013-01-28
221 Views
I have a table T with column A,B,C,...
The Primary Key is A,B,C
I need a select to list all A and the number of distinct B they have
So if the table is as follows :
A1  B1  C1
A1  B1  C2
A1  B2  C3
A1  B2  C4
A1  B2  C5
A2  B1  C1
A3  B1  C2

The result of the select is
A1,2
A1,1
A3,1
0
Question by:LeTay
[X]
###### Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

• Help others & share knowledge
• Earn cash & points

LVL 69

Accepted Solution

Scott Pletcher earned 500 total points
ID: 38827456
SELECT colA, count(distinct colb)
FROM dbo.tablename
GROUP BY colA
0

LVL 6

Expert Comment

ID: 38827466
SELECT tbl.A, COUNT(tbl.B) FROM
(
SELECT DISTINCT t.A,t.B FROM T
INNER JOIN T as T2 ON t.A = t2.A AND t.B = t2.B AND t.C = t2.C
)  tbl GROUP BY tbl.A

Haha ok Scott you win. I did not see the count so had to adjust mine. His answer is correct and easier
0

Author Comment

ID: 38828905
Indeed, first select is beautiful !
0

## Featured Post

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

### Suggested Solutions

Why is this different from all of the other step by step guides?  Because I make a living as a DBA and not as a writer and I lived through this experience. Defining the name: When I talk to people they say different names on this subject stuff l…
For both online and offline retail, the cross-channel business is the most recent pattern in the B2C trade space.
Using examples as well as descriptions, and references to Books Online, show the documentation available for date manipulation functions and by using a select few of these functions, show how date based data can be manipulated with these functions.
Via a live example, show how to extract information from SQL Server on Database, Connection and Server properties
###### Suggested Courses
Course of the Month6 days, 6 hours left to enroll