简体   繁体   中英

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?

You want count(distinct) :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM