-2

我想知道以下代码有什么问题:

cursor.execute("""SELECT calldate, dst, billsec, accountcode, disposition, 
                case when cast(substring(dst,4,1), unsigned) <= 5 then
                        billsec/60*%s as total
                else
                        billsec/60*%s as total
                end case
                FROM cdr where calldate >= '%s' and calldate < '%s' and disposition like '%s' and accountcode = '%s' and dst like '%s'""" %(rate_fixo, rate_movel, start_date, end_date, status, accountcode, destino))

尝试过这种方式并没有用:

cursor.execute("""SELECT calldate, dst, billsec, accountcode, disposition,
    case when cast(substring(dst,4,1), unsigned) <= 5 then 
        billsec/60*%s 
    else 
        billsec/60*%s 
    end as total
    FROM cdr where calldate >= '%s' and calldate < '%s' and disposition like '%s' 
    and accountcode = '%s' and dst like '%s'""" 
    %(rate_fixo, rate_movel, start_date, end_date, status, accountcode, destino))

错误:

“您的 SQL 语法有错误;请查看与您的 MySQL 服务器版本相对应的手册,以了解在 ' unsigned) <= 5 附近使用正确的语法,然后 billsec/60*0.1 否则 billsec/60*0.2 end as total FROM cdr w' 在第 1 行")

4

1 回答 1

2

MySQL 有两种 case 语句语法。一种用于查询,一种用于存储过程。您在查询中使用 sproc 版本,导致错误。查询版本中没有“结束案例”:

SELECT ..., CASE WHEN ... THEN... END 
                                      ^---no 'case' here
FROM ...

- - 跟进

同样,您不能给案例的组件起别名 - 这会动态地更改字段的名称,具体取决于案例的评估结果。您只能给整个 case 语句起别名:

SELECT ..., CASE WHEN ... THEN ... END AS total
                                      ^^^^^^^^^

例如

mysql> select case when 1=1 then 'a' else 'b' end case, 'hello';
                                                  ^^^^---syntax error         
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 'case, 'hello'' at line 1

mysql> select case when 1=1 then 'a' else 'b' end, 'hello';     
+-------------------------------------+-------+
| case when 1=1 then 'a' else 'b' end | hello |
+-------------------------------------+-------+
| a                                   | hello |
+-------------------------------------+-------+
1 row in set (0.00 sec)

mysql> select case when 1=1 then 'a' as 'a_val' else 'b' as 'b_val' end, 'hello
';
                                    ^^^^^^^^^^^--error  ^^^^^^^^^^^--- error
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 'a_val' else 'b' as 'b_val' end, 'hello'' at line 1

mysql> select case when 1=1 then 'a' else 'b' end as total, 'hello';           
+-------+-------+
| total | hello |
+-------+-------+
| a     | hello |
+-------+-------+
1 row in set (0.00 sec)
于 2012-09-16T03:28:51.540 回答