mysql - 使用 IF 语句进行交叉表查询

标签 mysql sql

我很好奇是否有人可以帮助我。

这是表格和字段: enter image description here

这是我得到的例子:

enter image description here

这就是我到目前为止所拥有的

Select ipno,
SUM(IF(retcode<100,0)) As '<100',
SUM(IF(retcode>=100   and retcode<200,0)) As '100s',
SUM(IF(retcode>=200  and retcode<300,0)) As '200s',
SUM(IF(retcode>=300 and retcode<400,0)) As '300s',
SUM(IF(retcode>=400,0)) As '400s'
From WebLog
Group By ipno;

但我不断收到此错误

ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ')) As '<100',
SUM(IF(retcode>=100   and retcode<200,0)) As '100s',
SUM(IF(retcod' at line 2

最佳答案

MySQL 中不需要 if():

Select ipno,
       SUM(retcode < 100) As `<100`,
       SUM(retcode >= 100 and retcode < 200) As `100s`,
       SUM(retcode >= 200 and retcode < 300) As `200s`,
       SUM(retcode >= 300 and retcode < 400) As `300s`,
       SUM(retcode >= 400) As `400s`
From WebLog
Group By ipno;

MySQL 将 bool 表达式视为数字上下文中的数字,“1”表示 true,d“0”表示 false。

此外,不要对列别名使用单引号。仅对日期和字符串常量使用单引号。

关于mysql - 使用 IF 语句进行交叉表查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50195710/

相关文章:

mysql - 在MySQL中使用复杂逻辑的动态查询

mysql - 子查询返回多于 1 行

mysql - SQL-选择 2 列的最新不同组合

mysql - 从mysql中的sql文件加载sql文件

php - 启动 Electron 应用程序并从网络浏览器(Chrome、Firefox)向其发送数据

mysql - nodejs mysql分页通过准备好的查询语句为每个未定义的属性返回错误

MySQL NOT IN 来自同一表中的另一列

java - jsp 中的过滤字符串不适用于括号 []

python - 根据列值加入 Pandas 数据框

sql - 我们在 Redshift 中的每晚工作需要 10-12 个小时才能运行