php 使用特定于计数的值左联接同一表

b4qexyjb  于 2023-01-19  发布在  PHP
关注(0)|答案(1)|浏览(92)

我有一个表,我想在其中统计按学校分组的姓名数量,统计学校是否有一个或两个性别,以及统计3个不同列中特定值的具体出现次数。我可以在两个不同的表中进行统计,但我想将它们连接起来,形成一个表
| F姓名|学校|性别问题|活动|活动2|活动3|
| - ------|- ------|- ------|- ------|- ------|- ------|
| 安|玛丽蒙特|F级|HJ|卢杰|天津|
| 彼得|玛丽蒙特|男|一百|二百|四百|
| 德鲁|圣休|男|一百|二百||
| 戴维斯|圣休|男|二百|||
| 凯特|坎皮恩|F级|四百|||
| 莫莉|坎皮恩|F级|四百|||
| 迈克|玛丽蒙特|男|八百|||
| 弗兰|坎皮恩|男|一百|二百||
这是我成功使用的两个单独的查询,它们创建了两个不同的结果集

$sql = "SELECT COUNT(FName) as cnt, COUNT(DISTINCT(Gender)) as gnd, school, COUNT(*) FROM entries WHERE school <> 'Unattached' GROUP BY school";
$sql = "SELECT COUNT(Events + Events2 + Events3) as events, school, COUNT(*) FROM entries WHERE (school <> 'Unattached') AND (Events = '100') OR (Events2 = '100') OR (Events3 = '100') GROUP BY school";
$result = $conn->query($sql);

我试过使用联合,但它只给我第二个查询的结果,名称的计数是关闭的。

$sql = "
SELECT COUNT(FName) as cnt, COUNT(Events + Events2 + Events3) as events, COUNT(DISTINCT(Gender)) as gnd, school 
FROM entries WHERE (school <> 'Unattached')
UNION
SELECT COUNT(FName) as cnt, COUNT(Events + Events2 + Events3) as events, COUNT(DISTINCT(Gender)) as gnd, school 
FROM entries WHERE (school <> 'Unattached') AND (Events = '100') OR (Events2 = '100') OR (Events3 = '100')
GROUP BY school";
$result = $conn->query($sql);

左连接没有给我任何结果,因为我不知道如何匹配这两个WHERE子句。
如何连接两个查询以获得具有以下结果的表
| 学校|参与者数量|性别数量|100号|
| - ------|- ------|- ------|- ------|
| 玛丽蒙特|三个|第二章|1个|
| 圣休|第二章|1个|1个|
| 坎皮恩|三个|第二章|1个|

e3bfsja2

e3bfsja21#

使用SUM()来计算条件为真的行数,这是因为布尔值为真时为1,为假时为0,所以SUM()得到这个计数。

SELECT school, 
    COUNT(*) AS num_participants, 
    COUNT(DISTINCT gender) AS num_genders, 
    SUM(events = '100' OR events2 = '100' OR events3 = '100') AS num_100
FROM entries
WHERE school != 'Unattached'
GROUP BY school

相关问题