gpt4 book ai didi

php - 使用一个 SQL 字符串进行行计数

转载 作者:行者123 更新时间:2023-11-29 09:32:04 25 4
gpt4 key购买 nike

我正在考虑是否可以使用一个 SQL 查询来计算不同列中的不同值。

我正在我的网站上制作图表,我希望它能够计算行中没有值,我正在考虑使用以下内容

$sql="SELECT incident.ppe, incident.induction, incident.actions, incident.ssops 
FROM incident WHERE ppe = 'No' OR induction = 'No' OR actions = 'No' OR ssops = 'No'
AND YEAR(date) = YEAR(CURDATE())
AND client_id = '$slcustom1'"

值为"is"和“否”。我的目标是回显我正在使用的图表值中每列的值。

var data = google.visualization.arrayToDataTable([
['', ''],
['PPE', 11], // Value 11 should be row counts of all the No's same with all values below
['Induction', 2],
['Actions', 2],
['SSOPs', 2]

目前,我对每个值执行 SQL 查询,但这使我的代码非常长且不整洁。任何建议,将不胜感激。分组依据也可以工作,但如何将每个结果回显到图表值

最佳答案

您可以组合 SUM()IF() 函数来计算所选行中的所有“否”,如下所示。

SELECT
SUM(IF(incident.ppe = 'No', 1, 0)),
SUM(IF(incident.induction = 'No', 1, 0)),
SUM(IF(incident.actions = 'No', 1, 0)),
SUM(IF(incident.ssops = 'No', 1, 0))
FROM incident

IF() 函数会将值 1 分配给条件为 true(属性值等于“否”)的行,并将 0 分配给其他行。然后,SUM() 将计算所有行的总数。因此,如果 ppe 中总共 9 行中有 5 个“否”,则 SUM() 结果将为 1+1+1+1+1+0+0+0+0=5

关于php - 使用一个 SQL 字符串进行行计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58492615/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com