Solved Count Unique Values in a Query (1 Viewer)

Bean Machine

Member
Local time
Today, 06:31
Joined
Feb 6, 2020
Messages
102
Hi All,

I am trying to count only the unique values in a specific column in my query. The field I am trying to count unique values for is the field "fld_CrNo". I have tried using SELECT DISTINCT but to no avail. There may be something more complex I need to implement in order to get it working. Any help would be greatly appreciated. The first image attached is before SELECT DISTINCT, the second is after SELECT DISTINCT, the third is my SQL, and then the fourth is what happens when I try to count them after SELECT DISTINCT. There should only be a count of 1 for "A", a count of 3 for "D" and a count of 2 for "I". Hopefully I have explained this well enough.
before SELECT DISTINCT.png
after SELECT DISTINCT.png
count after SELECT DISTINCT.png
 

cheekybuddha

AWF VIP
Local time
Today, 11:31
Joined
Jul 21, 2014
Messages
2,280
What do you get if you try:
SQL:
SELECT
  fld_IDA,
  fld_CrNo,
  COUNT(*) AS CountOfID
FROM YourTable
GROUP BY
  fld_IDA,
  fld_CrNo
;
 

cheekybuddha

AWF VIP
Local time
Today, 11:31
Joined
Jul 21, 2014
Messages
2,280
Ah, I think I see what you want.

Try:
SQL:
SELECT
  t.fld_IDA,
  COUNT(t.*) AS CountOfID
FROM (
  SELECT
    fld_IDA,
    fld_CrNo
  FROM YourTable
  GROUP BY
    fld_IDA,
    fld_CrNo
) t
GROUP BY
  t.fld_IDA
;
 

Bean Machine

Member
Local time
Today, 06:31
Joined
Feb 6, 2020
Messages
102
Ah, I think I see what you want.

Try:
SQL:
SELECT
  t.fld_IDA,
  COUNT(t.*) AS CountOfID
FROM (
  SELECT
    fld_IDA,
    fld_CrNo
  FROM YourTable
  GROUP BY
    fld_IDA,
    fld_CrNo
) t
GROUP BY
  t.fld_IDA
;
Thank you so much this worked perfectly! I really appreciate your help, and I hope you have a great day!
 

The_Doc_Man

Immoderate Moderator
Staff member
Local time
Today, 05:31
Joined
Feb 28, 2001
Messages
27,186
Just so that it would show up if someone did a search for it, that was an excellent example of a sub-query, Dave. (Always looking for those teaching moments!)
 

Users who are viewing this thread

Top Bottom