GeekGirl
GeekGirl

Reputation: 39

SQL query to count distinct count from 2 columns

I have SQL table named table

Document    Word
-------------------
doc1    Hello
doc1    Hi
doc1    Welcome
doc1    Hello
doc2    Welcome
doc2    Welcome
doc3    Hi
doc3    Hello
doc3    Good Luck

This means I have list of documents, each document contains some words, and I have raw for each word per each document, and if a word appeared twice in the same document I will have 2 raws. I want to get a list of distinct words with how many documents it appeared in, regardless how many times it appeared. So the output from this table should be

Hello: 2 --> which means it appeared in 2 documents
Hi: 2
Welcome: 2
Good Luck: 1

Can anyone please help me in writing the query that will return this result?

Upvotes: 2

Views: 68

Answers (1)

Gordon Linoff
Gordon Linoff

Reputation: 1269703

You want count(distinct):

select word, count(distinct document)
from t
group by word;

Upvotes: 3

Related Questions