这是我的桌子:
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和子查询,但是没有运气。
答案 0 :(得分:3)
一种方法是通过UNION
列中的名称fielded
和attended
列中的名称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());