MySQL表具有3列-区域,月份和收入,其值如下:
我编写了一个查询,将每个地区的收入按月分组
SET @sql = NULL;
SELECT GROUP_CONCAT(DISTINCT
CONCAT("SUM(CASE WHEN region = ", QUOTE(region)," THEN revenue ELSE 0 END) AS ",
CONCAT('`', region, '`')))
INTO @sql
FROM (SELECT * FROM TABLE1 WHERE region IS NOT NULL AND region <> '') RTD;
SET @sql = CONCAT("SELECT DATE_FORMAT(month, '%M-%Y') as Months, ", @sql, "
,SUM(revenue) as `Grand Total` FROM TABLE1
GROUP BY month ORDER BY month ASC" );
PREPARE region_stmt FROM @sql;
EXECUTE region_stmt;
在命令行和续集pro中产生这样的结果(这是期望的结果)
但是当我对带有python 2.7光标的Django 1.8使用相同的查询时,会产生错误
ProgrammingError:(1064,u'您的SQL语法有错误;请查看与您的MySQL服务器版本相对应的手册,以在\'SELECT GROUP_CONCAT(DISTINCT \ r \ n CONCAT(“ SUM (当region = \'“,第2行的'regio \'时为例)
我也使用了单引号而不是Quote(),但是得到了相同的结果
CONCAT("SUM(CASE WHEN region = '", region,"' THEN revenue ELSE 0 END) AS ",
Python代码
from django.db import connections
crsr = connections['rmd'].cursor()
crsr.execute(query)
答案 0 :(得分:0)
似乎您已经在转义引号和换行符,因此请避免在regiorn周围避免quote()
SET @sql = NULL;
SELECT GROUP_CONCAT(DISTINCT
CONCAT("SUM(CASE WHEN region = ", region," THEN revenue ELSE 0 END) AS ",
CONCAT('`', region, '`')))
INTO @sql
FROM (SELECT * FROM TABLE1 WHERE region IS NOT NULL AND region <> '') RTD;
您应该检查应用程序中sqlcode的真实内容,并使动态命令构建适应运行时应用程序环境的功能