所有我需要的是與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'在選擇列表中無效?
歡迎任何建議。 謝謝,
我有同樣的問題,看來。任何解決方案 –
http://stackoverflow.com/questions/23902172/sqlalchemy-query-in-mssql-programmingerror-invalid-odbc-bug –