2014-02-13 105 views
0

所有我需要的是與A組簡單的查詢BY CASE像需要SQLAlchemy的查詢與GROUP BY CASE

SELECT 
    COUNT([Personnel].[PERSONNEL_ID]) AS value, 
    CASE 
    WHEN ([Personnel].[T_FIRSTNAME] = 'John') THEN 'John' 
    ELSE 'somethingelse' 
    END AS somelabel 
FROM [Personnel] 
GROUP BY 
    CASE 
    WHEN ([Personnel].[T_FIRSTNAME] = 'John') THEN 'John' 
    ELSE 'somethingelse' 
    END 

在SQLAlchemy中我的查詢看起來是這樣的:

case_groups = case(
    [(HrPersonnel.T_FIRSTNAME=='John', 'John')], 
    else_='somethingelse' 
) 

volunteers = session_mssql.query(
    func.count(HrPersonnel.S_HR_PERSONNEL_ID).label('value'), 
    case_groups.label('somelabel'))\ 
    .group_by(case_groups)\ 
    .all() 

MSSQL服務器執行查詢沒有任何問題(engine.connect().execute(text_query))

但Sqlalchemy ORM查詢給我一個錯誤。

File "c:\projects\sa_test\eggs\sqlalchemy-0.9.2-py2.7.egg\sqlalchemy\engine\default.py", line 425, in do_execute cursor.execute(statement, parameters) sqlalchemy.exc.ProgrammingError: (ProgrammingError) ('42000', "[42000] [Microsoft][ODBC SQL Server Driver][SQL Server] Column 'Personnel.T_FIRSTNAME' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause. (8120) (SQLExecDirectW); [42000] [Microsoft][ODBC SQL Server Driver][SQL Server]Statement(s) could not be prepared. (8180)") u'SELECT count([Personnel].[PERSONNEL_ID]) AS value, CASE WHEN ([Personnel].[T_FIRSTNAME] = ?) THEN ? ELSE ? END AS somelabel \nFROM [Personnel] GROUP BY CASE WHEN ([Personnel].[T_FIRSTNAME] = ?) THEN ? ELSE ? END' ('John', 'John', 'somethingelse', 'John', 'John', 'somethingelse')

爲什麼'Personnel.T_FIRSTNAME'在選擇列表中無效?

歡迎任何建議。 謝謝,

+0

我有同樣的問題,看來。任何解決方案 –

+0

http://stackoverflow.com/questions/23902172/sqlalchemy-query-in-mssql-programmingerror-invalid-odbc-bug –

回答

1

我本人沒有答案(雖然未來的讀者可能想檢查SQLAlchemy Google Group上的this thread),但我最近有類似的問題,並找到了解決方法。

不是直接執行查詢,而是將其轉換爲字符串並執行該查詢。例如:

session.execute(
    str(query.selectable.compile(compile_kwargs={'literal_binds': True})) 
).fetchall()