17

I have this table:

A B
1 4
2 5
3 6
1 4
2 4
3 4

How could I output:

A count
1 1
2 2
3 2

i.e. count records with distinct value.

I have read that in mysql I could do:

select A, count(distinct B) from table group by A

How can I transform this to Google Spreadsheet Query language?

sites
  • 21,417
  • 17
  • 87
  • 146

4 Answers4

10

=QUERY(unique(A1:B7), "select Col1, count(Col2) group by Col1")

generally, the first part makes a "table" with only unique values and the select counts and groups.

marc meyer
  • 530
  • 6
  • 6
8

One way to do it is

1- In Column C1, enter a formula =Unique(A1:A6). This will give you the unique items in Column A

enter image description here

2- Then in Column D1, enter =COUNTUNIQUE(FILTER($B$1:$B$6,$A$1:$A$6=C1)) and drag it down

enter image description here

Pankaj Jaju
  • 5,371
  • 2
  • 25
  • 41
  • is possible to use that formula with AJAX? I am using this https://developers.google.com/chart/interactive/docs/querylanguage – sites Mar 16 '14 at 21:07
  • I'm not really an expert in this; but I've seen people applying formulas and fetching the values. Would suggest some Google Rnd – Pankaj Jaju Mar 16 '14 at 21:34
2

If you want to do it with a QUERY, it is possible. Indeed, the QUERY function will give you a table as a result; You have to set another QUERY to set the range of the final function.

In your case:

=QUERY(
UNIQUE(QUERY(A1:B7;"SELECT * WHERE A is not null ORDER BY A"));
"SELECT Col1, count(Col2) WHERE Col1 is not null GROUP BY Col1")

As you can see, the first QUERY set the table for the second one. This is why you have to use ColX and not A for the final QUERY.

0

You just add sum function on the query.

SUM(QUERY(A1:B7,"SELECT COUNT(B) GROUP BY B LABEL COUNT(B) ''"))

MaxiGui
  • 6,190
  • 4
  • 16
  • 33
  • Note: answers that are very brief and/or are questions back to the poster should probably be comments. You only need 50 rep points to comment under a question - could you move this there? – Tyler2P Dec 04 '20 at 10:07