计算多列中的不同值

时间:2016-09-30 09:30:27

标签: mysql sql phpmyadmin

我有一个数据库表

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

我想在procLeader和procChecker的多个列中计算不同的变量,所以我想显示列名total 3,因为ben出现2

我到目前为止所做的是尝试将union两个列合并为一个,但现在无法获得如何计算。 我的问题:

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 

或许还有另一种计算不同变量的方法?谢谢 我想最后的结果是这样的

 total| 
 -----+
 3    |

5 个答案:

答案 0 :(得分:2)

您必须将查询包装在子查询中:

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

答案 1 :(得分:2)

在两列之间使用UNION删除重复项COUNT(*)以获取计数结果。

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

无需使用 DISTINCT ,因为 UNION 运算符会从结果集中删除重复项

答案 2 :(得分:1)

试试这个:

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

答案 3 :(得分:0)

使用count(distinct)

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

答案 4 :(得分:0)

试试这个。如果您有任何疑虑或问题,请告诉我们。

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