【问题标题】:How make a calculation table from 2 tables如何从 2 个表中制作一个计算表
【发布时间】:2020-02-25 09:03:04
【问题描述】:

我有 2 个表,想制作一个百分比表。

select a.claim_by,
count(select count (claim_by) from itcorp_first_response a) + (select count (claim_by) from itcorp_reopen_response b) as total_response,
count(select count (response_time > minute (response_time -30)) from itcorp_first_response a) + (select count (response_time > minute (response_time -30)) from itcorp_reopen_response b) as total_target,
count(select count (response_time > minute (response_time +30)) from itcorp_first_response a) + (select count (response_time > minute (response_time +30)) from itcorp_reopen_response b) as total_untarget
from itcorp_first_response a, itcorp_reopen_response b
where a.claim_by in ('Petrus Asbirianto','Ifnu Muhardhi','Riko Rachmat Saleh','Muhammad Irsan','Dion Laksmana') 
and a.claim_by = b.claim_by
GROUP BY a.claim_by;

但出现以下错误:

QL 错误 [1064] [42000]: (conn=78589) 您的 SQL 中有错误 句法;检查与您的 MariaDB 服务器相对应的手册 在 'select count (claim_by) from 附近使用正确语法的版本 itcorp_first_response a) + (select count (claim_by)' 在第 2 行

【问题讨论】:

  • 今日提示:始终使用现代、明确的JOIN 语法。更容易编写(没有错误),更容易阅读和维护,如果需要更容易转换为外连接!
  • 首先缺少括号,例如这里的开头和结尾括号:count((select count (claim_by) from itcorp_first_response a) + (select count (claim_by) from itcorp_reopen_response b)) as total_response,.
  • 两个关联子查询与聚合, GROUP BY?
  • 向我们展示一些示例表数据和预期结果 - 作为格式化文本,而不是图像。 minimal reproducible example
  • 这看起来过于复杂。并且错了。 Q1:select count (claim_by) from itcorp_first_response a 计算表 itcorp_first_response 中出现的所有非空 claim_by。 Q2:select count (claim_by) from itcorp_reopen_response b 对表 itcorp_reopen_response 执行相同的操作。 select count( (Q1) + (Q2) ) 仅当两个结果都不为空时才计算结果。然后为主查询中的每一行评估相同的值。这似乎没有意义。

标签: sql mariadb


【解决方案1】:
count(select count (claim_by) from itcorp_first_response a) +
     (select count (claim_by) from itcorp_reopen_response b)
   as total_response,

-->

( SELECT COUNT(*) FROM a ) +
( SELECT COUNT(*) FROM a ) as total_response

这应该可以避免 1064 错误。)

不要数数。

使用COUNT(*) 而不是COUNT(x),除非您需要检查x 以获取NULL

(response_time > minute (response_time -30))

什么是数据类型? (在这里提问时,请提供SHOW CREATE TABLE。)如果是DATETIMETIMESTAMP,请说类似

( response_time > NOW() - 30 MINUTE )

然后,意识到COUNT() 检查是否存在行;它不符合事实,但 SUM 符合:

SELECT  count (response_time > minute (response_time -30))
            from  itcorp_reopen_response b

-->

SELECT  SUM(response_time > NOW() - 30 MINUTE)
            from  itcorp_reopen_response b

请不要重复使用别名(ab);它使读者感到困惑。

进行这些修复并向我们展示您所拥有的;可能还有更多需要“修复”的地方。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-20
    • 2014-01-27
    • 2022-12-18
    • 2016-08-16
    • 1970-01-01
    相关资源
    最近更新 更多