从下表中,我想计算1)不同名称的数量和2)每个名称的出现次数。
+------+------+-------+-------+-------+-------+-------+
| date | job |person1|person2|person3|person4|person5|
+------+------+-------+-------+-------+-------+-------+
| mon | clean| Matt | Bruce | Alan |Emilce | Linda |
+------+------+-------+-------+-------+-------+-------+
| tu | write| Bruce | Matt | Matt | Alan | Linda |
+------+------+-------+-------+-------+-------+-------+
| wen | mend | Bruce |Emilce | Matt | Matt | Linda |
+------+------+-------+-------+-------+-------+-------+
| fri | sew | Matt | Linda |Emilce | Alan | Alan |
+------+------+-------+-------+-------+-------+-------+
输出应为:
姓名:5
每个名称的出现次数:
+------+------+
| Alan | 4 |
+------+------+
| Bruce| 3 |
+------+------+
|Emilce| 3 |
+------+------+
| Linda| 4 |
+------+------+
| Matt | 5 |
+------+------+
我一直在尝试
SELECT user, count(*) AS count
FROM (
SELECT person1 AS user FROM mytable
UNION ALL
SELECT person1 FROM mytable
UNION ALL
SELECT person3 FROM mytable
UNION ALL
SELECT person4 FROM mytable
UNION ALL
SELECT person5 FROM mytable
) AS all_users
GROUP BY user
ORDER BY user
但我不知道如何知道表中的名字数量,我想知道数组中每个名字的出现次数。
答案 0 :(得分:1)
这是你想要的吗?
SELECT count(distinct user) as NumNames
FROM (
SELECT person1 AS user FROM mytable
UNION ALL
SELECT person1 FROM mytable
UNION ALL
SELECT person3 FROM mytable
UNION ALL
SELECT person4 FROM mytable
UNION ALL
SELECT person5 FROM mytable
) all_users
答案 1 :(得分:-1)
以上代码实际上正在运作
mysql_result($ Persons,0,1)确实是表中存在的名称总数
因此,您可以循环获取所有名称/出现对
我没注意到。
道歉。
$Persons=mysql_query('SELECT user, count(*) AS count
FROM (
SELECT person1 AS user FROM mytable
UNION ALL
SELECT person1 FROM mytable
UNION ALL
SELECT person3 FROM mytable
UNION ALL
SELECT person4 FROM mytable
UNION ALL
SELECT person5 FROM mytable
) AS all_users
GROUP BY user
ORDER BY user');
$TotalPersons=mysql_result($Persons,0,1);
for ($i=0;$i<=$TotalPersons;$i++) {
$Name[$i]=mysql_result($Persons,$i+1);
$Occurences[$i]=mysql_result($Persons,$i+1,1);
echo "<br> Number".$i.": ".$Name[$i].": ".$Occurences[$i]."<br>";
}