Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
Solved

# Count statement with group...

Posted on 2014-12-17
Medium Priority
113 Views
Hello, can someone let me know how I can write a statement that firsts groups by column A and then give a count of values in column B. For eg;
Col-A(Cust ID)         Col-B
100                          Closed
200                          Active
200                          Active
100                          Closed
300                          Open
400                          Progress
500                          Active

Output I am looking for is:
Col-B   count
Closed  1
Active    2
Open     1
Progress 1

Thanks for the help.

A
0
Question by:aej1973
[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
• 2
• 2

LVL 66

Expert Comment

ID: 40506257
> firsts groups by column A and then give a count of values in column B.
Not quite sure I'm following your logic here, as the sample data set doesn't translate to the data mockup.
There are seven rows in your sample data set, and only five in the result set.
``````Select ColB, COUNT(ColB) as the_count
FROM YourTable
GROUP BY ColB
``````
0

Author Comment

ID: 40506280
I am sorry if I did not make myself clear. Let me explain;

The first grouping should be with reference to  Col-A. So the outcome would be:
Col-A Col-B
100    Closed
200    Active
300    Open
400    Progress
500   Active

The next grouping and count should be with reference to col-B, the output will be;
Col b      count
Closed     1
Active      2
Open       1
progress 1

How can these two steps be combined into one query? Thanks for taking a look at it.

A
0

LVL 66

Accepted Solution

Jim Horn earned 2000 total points
ID: 40506313
Okay, try this then:
``````IF OBJECT_ID('tempdb..#tmp') IS NOT NULL
DROP TABLE #tmp
GO

CREATE TABLE #tmp (ColA int, ColB varchar(25))

INSERT INTO #tmp (ColA, ColB)
VALUES
(100, 'Closed'), (200, 'Active'),  (200, 'Active'),(100, 'Closed'),
(300, 'Open'),(400, 'Progress'),(500, 'Active')

SELECT a.ColB, COUNT(a.ColB) as [Count]
FROM (
Select ColA, ColB
FROM #tmp
GROUP BY ColA, ColB) a
GROUP BY a.ColB
``````
0

LVL 25

Expert Comment

ID: 40508156
All you need is to count DISTINCT values, like this:
``````Select ColB, COUNT(DISTINCT ColA) as the_count
FROM YourTable
GROUP BY ColB
``````
0

Author Closing Comment

ID: 40508274
Works! Thank you.
0

## Featured Post

Question has a verified solution.

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

Creating and Managing Databases with phpMyAdmin in cPanel.