在1个查询中计算同一mysql行中的2个不同字段

时间:2019-03-23 23:31:20

标签: mysql

这是我的桌子:

id     |    fielded    |    attended
=====================================
1           Greg            Chris
2           James           Chris
3           Greg            James

我的查询如下:

Select DISTINCT(fielded), count(fielded) as fielded_count FROM fielded_calls group by fielded

我想看到的输出是:

fielded    |    fielded_count    |    attended_count
====================================================
Chris           0                     2
Greg            2                     0
James           1                     1 

如何添加基于“字段”列中唯一名称的出席人数?我尝试了UNION和子查询,但是没有运气。

1 个答案:

答案 0 :(得分:3)

一种方法是通过UNION列中的名称fieldedattended列中的名称LEFT JOIN列出表中所有唯一名称的列表。然后可以将此派生表SELECT n.name AS fielded, COUNT(DISTINCT c1.id) AS fielded_count, COUNT(DISTINCT c2.id) AS attended_count FROM (SELECT fielded AS name FROM fielded_calls UNION SELECT attended FROM fielded_calls) n LEFT JOIN fielded_calls c1 ON c1.fielded = n.name LEFT JOIN fielded_calls c2 ON c2.attended = n.name GROUP BY fielded 添加到原始表中,以获得所需的计数:

fielded     fielded_count   attended_count
Chris       0               2
Greg        2               0
James       1               1

输出:

const petsArr = ['cat', 'dog', 'rabbit', 'hamster', 'parrot'];

const petsList = (petsListLength => () => {
  let currentIndex = Math.floor(Math.random() * (petsListLength + 1));
  const randomPetsList = [];
  while (currentIndex < petsListLength) {
    randomPetsList.push(petsArr[currentIndex]);
    currentIndex += Math.floor(Math.random() * (petsListLength - 1)) + 1;
  }
  return randomPetsList;
})(petsArr.length);

console.log(petsList());

Demo on dbfiddle