I am trying to get this query to work and is throwing up the error that subqueries cannot be used in the expression...
SELECT qrySrcReq.MDC_Office,
Count(qrySrcReq.ReqNumKey) AS Ct_ReqNRs,
Count(IIf([3PL]="yes",0)) AS Ct_3PLReqNrs,
Count(IIf([3PL] Is Null,0)) AS Ct_OtherReqNrs,
Sum(IIf([3PL]="yes",[BO_Qty],0)) AS Sum_3PLBOs,
Sum(qrySrcReq.BO_Qty) AS BO_Qty,
IIf([qrySrcReq]![Priority] Like "04*","3PL","Tactical") AS Strategy
FROM qrySrcReq
WHERE (((qrySrcReq.Priority) Like "04*") AND ((qrySrcReq.[3PL Status])="C")) OR (((qrySrcReq.Priority) Is Not Null) AND ((qrySrcReq.[3PL Status]) Is Null Or (qrySrcReq.[3PL Status])=""))
GROUP BY qrySrcReq.MDC_Office,
IIf([qrySrcReq]![Priority] Like "04*","3PL","Tactical");
The line that is throwing the error is:
Sum(IIf([3PL]="yes",[BO_Qty],0)) AS Sum_3PLBOs
Is there another way to right this to get it to work? Thanks.
Change
Sum(qrySrcReq.BO_Qty) AS BO_Qty
to
Sum(qrySrcReq.BO_Qty) AS Sum_BO_Qty
Related
In the query below, I keep getting the error "An expression of non boolean type specified in a context where a condition is expected near End". Down below is my code I'm not trying to return the rows where the pk__street_name == NULL in the join. But I get the error listed above. How can I fix this.
result = session.query(
tamDnRangeMap, tamStreet
).join(tamStreet)
.filter(
case(
[(tamDnRangeMap.pk_street_name == NULL, 0)],
else_ = 1
)
).all()
First remark is that you don't want equality comparisons anywhere near NULL in SQL, it is done with IS or IS NOT.
Once you know that, you can use SQLAlchemy's is_ or isnot* operators.
All in all, you're using CASE where you don't really need it, put the IS NOT NULL condition in filter directly.
result = (
session.query(tamDnRangeMap, tamStreet)
.join(tamStreet)
.filter(tamDnRangeMap.pk_street_name.isnot(None))
.all()
)
* NB. isnot has been deprecated and is replaced by is_not since SQLAlchemy 1.4, but the question uses case with list of whens which was also deprecated in 1.4.
I am trying to select from a table the column name, but would like to get it all caps, using UPPER.
I would like to to it without using Knex raw SQL, but it doesn't work.
That's what I am trying to do:
const usersJornadasComites = await Database.table('tb_usuario_jornada')
.where('tb_usuario_jornada.jornada_id', lastJornad.id)
.where('tb_usuario_jornada.comite_id', params.id)
.where('tb_usuario_jornada.ativo', 1)
.select(
'tb_usuario.id',
'UPPER(tb_usuario.nome)',
'tb_usuario.email',
'tb_usuario.celular',
'tb_usuario.dt_nascimento',
'tb_usuario_jornada.criado_em',
'tb_usuario.id',
'tb_usuario_jornada.usuario_id'
)
.leftJoin(
'tb_usuario',
'tb_usuario_jornada.usuario_id',
'tb_usuario.id'
)
It gives me an error saying that UPPER(tb_usuario.nome) is not a valid column name.
Any ideas?
Many thanks,
Gines
just to inform if somebody else has the same issue.
The solution I used was to instead of using ORM syntax, I used the knex.raw select and it worked properly.
U can try to UPPER(tb_usuario.nome) as nome
I'm using Sphinx, and I'm trying to execute the next query in mysql:
SELECT *
FROM `index_efemerides`, `index_programas`, `index_guias_para_el_aula`, `index_producciones_interactivas`
WHERE MATCH('(#(titulo,descripcion,etiquetas) nuevo)')
OPTION `field_weights` = (index_programas.titulo=100, index_programas.etiqueta=15, index_programas.descripcion=5, index_producciones_interactivas.titulo=53, index_producciones_interactivas.etiqueta=13, index_producciones_interactivas.descripcion=5, index_guias_para_el_aula.titulo=52, index_guias_para_el_aula.etiqueta=12, index_guias_para_el_aula.descripcion=5, index_efemerides.titulo=51, index_efemerides.etiqueta=11, index_efemerides.descripcion=5)
But I'm getting the next error msg:
sphinxql: syntax error, unexpected SUBKEY, expecting '=' near '.titulo=100, index_programas.etiqueta=15, index_programas.descripcion=5, index_producciones_interactivas.titulo=53, index_producciones_interactivas.etiqueta=13, index_producciones_interactivas.descripcion=5, index_guias_para_el_aula.titulo=52, index_guias_para_el_aula.etiqueta=12, index_guias_para_el_aula.descripcion=5, index_efemerides.titulo=51, index_efemerides.etiqueta=11, index_efemerides.descripcion=5)'
If I remove the dots it seems to work (not really sure because if i invent a field name, it doesn't show me any error). But i need to set the field weights different per table.
I've just found index_weight property. A possibility is to complement index_weight with field_weights like this:
SELECT * FROM `index_efemerides`, `index_programas`, `index_guias_para_el_aula`, `index_producciones_interactivas` WHERE MATCH('(#(titulo,descripcion,etiquetas) nuevo)') OPTION `field_weights` = (titulo=100, etiqueta=15, descripcion=5), `index_weights` = (index_programas=100, index_guias_para_el_aula=50, index_efemerides=75, index_producciones_interactivas=25);
Not pretty sure of the resulting weight.
I've been trying to figure out how to pass the request.args to sqlalchemy filter.
I thought this should work:
model.query.filter(**request.args).all()
But it's throwing the error:
TypeError: <lambda>() got an unexpected keyword argument 'userid'
When userid or any other get arg is present.
According to this post - https://stackoverflow.com/questions/19506105/flask-sqlalchemy-query-with-keyword-as-variable - you can pass a dict to the filter function.
Any ideas what I'm doing wrong?
Many thanks :)
UPDATE: Many thanks to the poster below, however now it's throwing the following error:
ProgrammingError: (ProgrammingError) (1064, "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 ') ORDER BY tblclients.clientname' at line 3") 'SELECT favourites.id AS favourites_id, favourites.userid AS favourites_userid, favourites.clientid AS favourites_clientid, favourites.last_visit AS favourites_last_visit \nFROM favourites INNER JOIN tblclients ON tblclients.clientid = favourites.clientid \nWHERE favourites.userid = %s ORDER BY tblclients.clientname' ([u'41'],)
Any ideas?
First, you have to use filter_by, not filter.
Second, Flask request.args uses a MultiDict, a dict with the values inside a list, allowing more than one value for the same key, because the same field can appear more than once in a querystring. You got the error because the SQL query got the [u'41'] when it expected only '41'. You can use request.args.to_dict() to fix that:
model.query.filter_by(**request.args.to_dict()).all()
Use filter_by:
model.query.filter_by(**request.args).all()
filter is used like this: query.filter(Class.property == value) while filter_by is used like this: query.filter_by(property=value) (the first one being an expression and the latter one being a keyword argument).
filter_by(**request.args) doesn't work well if you have non-model query parameters, like page for pagination, otherwise you get errors like these:
InvalidRequestError: Entity '<class 'flask_sqlalchemy.JobSerializable'>' has no property 'page'
I use something like this which ignores query parameters not in the model:
builder = MyModel.query
for key in request.args:
if hasattr(MyModel, key):
vals = request.args.getlist(key) # one or many
builder = builder.filter(getattr(MyModel, key).in_(vals))
if not 'page' in request.args:
resources = builder.all()
else:
resources = builder.paginate(
int(request.args['page'])).items
Considering a model with a column called valid, something like this will work:
curl -XGET "http://0.0.0.0/mymodel_endpoint?page=1&valid=2&invalid=whatever&valid=1"
invalid will be ignored, and page is available for pagination and best of all, the following SQL will be generated: WHERE mymodel.valid in (1,2)
(get the above snippet for free if you use this boilerplate-saving module)
You can:
http://localhost:5000/filter-test?var=test
query_dict = request.args.to_dict()
print(query_dict)
{'var': 'test'}
print(query_dict['var'])
var
I am having a trouble with executing an HQL query like this:
select new myPackage.view.CoverDocumentReportView(Re.code AS fulCd,
Re.creditPrice AS crtprc,
Re.debitPrice AS dbtprc,
(Re.debitPrice - Re.debitPrice) AS redbtprc,
(Re.creditPrice- Re.creditPrice) AS recrtprc,
(Re.debitPrice-Re.creditPrice) AS rem)
from
(select fullCode as code,
sum(creditPrice) as creditPrice ,
sum(debitPrice) as debitPrice
from DocumentMaster DM,
DocumentAccount DA,
Tree T ,
AccountTree AT,
DocumentDetailed DD
where DM.id = DA.documentMaster and
DA.accountTree = T.id and
DA.accountTree = AT.id and
DD.documentAccount = DA.id
group by DA.accountTree ) As Re
1)
If I execute this like:
SQLQuery crit = (SQLQuery) session
.createSQLQuery(sql).setResultTransformer(Transformers.aliasToBean(CoverDocumentReportView.class));
ArrayList<CoverDocumentReportView> li = (ArrayList<CoverDocumentReportView>) crit.list();
ERROR 2012-12-22 14:16:19,838 [http-8080-1] org.hibernate.util.JDBCExceptionReporter : 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 '.datx.web.accounting.view.CoverDocumentReportView(Re.code AS fulCd,
Re.creditP' at line 1
2)
If I execute it with this:
Query query = session.createQuery(sql).setResultTransformer(Transformers.aliasToBean(CoverDocumentReportView.class));
ArrayList<CoverDocumentReportView> li = (ArrayList<CoverDocumentReportView>)query.list();
The error will be:
ERROR 2012-12-22 14:51:46,709 [http-8080-1] org.hibernate.hql.ast.ErrorCounter : line 1:224: unexpected token: (
ERROR 2012-12-22 14:51:46,709 [http-8080-1] org.hibernate.hql.ast.ErrorCounter : line 1:308: unexpected token: sum
What is the problem?
SQL and HQL are two different languages.
HQL doesn't support subqueries in from clauses, so this query can't be an HQL query.
And SQL doesn't know about Java objects, and doesn't have any new() function allowing to create them, so the query is not a valid SQL query either.
Make it a valid SQL query, execute it using createSQLQuery(), then iterate through the results and create instances of your objects from the returned rows. Or use a result transformer as you're doing, which will do that for you. the result transformer will use the aliases you assigned to the returned columns of the SQL query to create beans for you. You don't need any new CoverDocumentReportView() in the query to make that work. Read the javadoc for details.