简体   繁体   中英

Count distinct values in multiple columns

I have a database table

 projectNo| process | procLeader | procCheker  |  
 ---------+---------+------------+-------------+
 16090001 | ANM     | ari        | barry       |
 16090001 | BLD     | ben        | ben         |

I want to count distinct variables inside multiple columns procLeader and procChecker, so i want to display column name total 3 as ben appears 2

What i did so far is tried to union both columns into one but cant get how to count it now. My query:

select distinct `procLeader`
as tot from process as tot where projectNo=16090016
union
select distinct `procChecker`
from process from process as tot where projectNo=16090016 

Or maybe there is another way to count distinct variables? Thanks I want to final result be like this

 total| 
 -----+
 3    |

You have to wrap your query in a subquery:

select count(distinct tot) as total
from (
  select distinct `procLeader` as tot 
  from process  
  where projectNo=16090016
union
  select distinct `procChecker`
  from process 
  where projectNo=16090016) as t

Use UNION between the two columns to remove duplicate and COUNT(*) to get count result.

SELECT COUNT(*) as Total
FROM
( SELECT `procLeader` FROM process where projectNo=16090016
  UNION
  SELECT `procCheker` FROM process where projectNo=16090016
) AS tmp

No need to use DISTINCT as UNION operator removes duplicates from resultset

Try this:

SELECT COUNT(*) Total FROM (
SELECT procLeader AS tot FROM process WHERE projectNo=16090016
UNION
SELECT procChecker FROM process WHERE projectNo=16090016) t;

Use count(distinct)

select projectNumber, count(distinct procleader) as C1, count(distinct procChecker) as C2
from Table1
where projectNumber = 16090016 
group by projectNumber

Try this. Please let us know if you have any concerns or que.

select (count(distinct procChecker)+count(distinct procLeader)) as `Total` 
from process  
where projectNo=16090001 

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