I'm trying the standard SELECT ... AS call to rename a column in query output with the Python Salesforce API and it's throwing following error:
... unexpected token: 'AS'", 'errorCode': 'MALFORMED_QUERY'}
So far most native language calls from SOQL have been working in the API and it seems, from here, that SELECT ... AS is valid SOQL.
Query outline:
from simple_salesforce import Salesforce
sf = Salesforce(username=myusername, password=mypassword, security_token=mytoken)
query = "select closedate as Date from opportunity"
query_list = sf.query_all(query)['records']
edit
error remains even after putting the new column name within quotes as advised in above link:
query = "select closedate as \"Date\" from Opportunity"
Thanks
As Terminus mentioned, SOQL field aliasing is not possible in SOQL in most contexts, including yours. The only case in which I have seen aliasing working in SOQL is in aggregate queries. For example, in apex you could write:
AggregateResult myResult = [SELECT count(Id) SpecialName FROM Contact];
system.debug(myResult);
and receive the result:
DEBUG|AggregateResult:{SpecialName=1630}
In python via simple-salesforce it would look like this:
sf.query_all('SELECT count(Id) SpecialName FROM Contact')
with the result:
OrderedDict([('totalSize', 1),
('done', True),
('records',
[OrderedDict([('attributes',
OrderedDict([('type', 'AggregateResult')])),
('SpecialName', 6587)])])])
Please mark as answered if this answer your question.
The syntax seems to be incorrect.
Try query = "select closedate <insert alias> from Opportunity" according to the alias notation documented here : https://developer.salesforce.com/docs/atlas.en-us.soql_sosl.meta/soql_sosl/sforce_api_calls_soql_alias.htm
Related
I want to export all items of type Order, which contain a coupon code named 'TESTCOUPON'. However, when I try to do it, I get this error:
ERROR line 4 at main script: error executing code line at 4 : SQL search error - ORA-00932: inconsistent datatypes: expected - got BLOB
query = 'SELECT item_t0.PK FROM orders item_t0 WHERE ( item_t0.p_appliedcouponcodes = 'TESTCOUPON') AND (item_t0.TypePkString IN (?,?,?) )', values = [8796099149906, 8796099215442, 8796098756690]
I assume from the error that the coupon is stored in a Collection/List - how would I filter by it in this case?
The FlexibleSearch line looks like this:
SELECT {C:PK} FROM {Order as C} WHERE {C:appliedCouponCodes} = 'TESTCOUPON'
I tried using the PK of the coupon code, but it doesn't work either and it presents the same error. I tried using LIKE '%TESTCOUPON%' but then it said 'expected CHAR got BLOB'.
As per the Table structure CouponRedemption having reference of Order
.
so correct query will be as below.
select { o.code },{o.pk},{cr.couponCode} from {Order as o Join CouponRedemption as cr on {cr.order}={o.pk}} where {code}='TESTCOUPON'
Output:
code PK p_couponcode
1050156308 9499773075501 BUY4
1044303645 9499775172653 BUY4
1042057811 9499796897837 BUY4
1049853832 9499798863917 BUY4
This is my first try at using the Power Query... I've build a "dynamic" query in which I can change the retrieved fields as well as the filtering fields and values to be used by the query.
It's working perfectly on my computer but as soon as I try to execute it on another computer, I get the "Please rebuild this data combination" error. I saw some post saying I'll have to kind of split my query but I have not been able to figure it out.
Here is what my 2 tables look like:
Condition and fields selection
and here is my Query with the error:
Query
This might not be very elegant, but it allow me, thru a VBA script, to generate the list of fields to be retrieved and to generate the condition to be used by the SQL.
Any idea why it's not working on the other computers or how to improved the solution I'm using?
Thank you!
Notes:
Hi, all my Privacy Level are already set to 'None'.
I've tried to parametrize my code but I can't figure how. The Where condition is dynamic: it could be Where Number = "1234" but in other condition, the where might be like: 'Where Assignee = "xyz"'.
Here is a simplified example of my code:
let
Source = Sql.Database("xxxx", "yyyy", [Query=
"Select network, testid
from CM3T1M1 "
& paramConditions[Conditions]{0} &
" "])
in
Source
rebuild query, Formula.Firewall
That's a feature to prevent prevent accidentally leaking data. You can change the privacy level to ignore it
See also: docs.microsoft/dataprivacyfirewall
Is the dynamic query inserting those cells into the SQL query ? Report Parameters are nice for letting the user change variables without having to re-edit the query.
Parameterized native SQL queries
from: https://blog.crossjoin.co.uk/2016/12/11/passing-parameters-to-sql-queries-with-value-nativequery-in-power-query-and-power-bi/
let
Source = Sql.Database("localhost", "Adventure Works DW"),
Test = Value.NativeQuery(
Source,
"SELECT * FROM DimDate
WHERE EnglishMonthName=#MonthName AND
EnglishDayNameOfWeek=#DayName",
[
MonthName = "March",
DayName = "Tuesday"
]
)
in
Test
Dynamic Power Query version of SQL Query
To dynamically generate this SQL Query
select NUMBER, REQUESTED_BY from SourceTable
where NUMBER = 404115
Table.SelectRows is your Where.
SelectColumns is your select
let
Source = ...,
filterByNum = 404115,
columnNames = {"NUMBER", "REQUESTED_BY"},
removedColumns = Table.SelectColumns(
Source, columnNames, MissingField.Error
),
// I used 'MissingField.Error' so you know right away
// if there's a typo or bug
// assuming you are comparing Source[NUMBER]
filteredTable = Table.SelectRows(
Source, each [NUMBER] = filterByNum
)
in
filteredTable
I'm new to Flask and have started designing a front end for an inventory management database using Flask-AppBuilder.
I have created several models and have have managed to display my sqlite data in tables using Flask-AppBuilder's views.
However, I don't seem to be able to find the equivalent of SQLite WHERE clause to filter or "restrict" column data. I've been reading a lot about sqlalchemy, filters, queries but this has left me more confused that anything else and the explanations seem to be extremely elaborate and complicated to do something which is extremely simple.
Assuming we reproduce the following SQLite query in Flask-AppBuilder:
SELECT Field_A
FROM Table_A
WHERE Field_A = 'some text'
with:
result = session.query(Table_A).filter_by(Field_A = 'some text').all()
Where does the above line of code go in my app?
Considering I have the following Class:
class Table_A(Model):
id = Column(Integer, primary_key=True)
Field_A = Column(String)
def __repr__(self):
return self
and View:
class Table_AView(ModelView):
datamodel = SQLAInterface(Table_AView)
label_columns = {'Field_A':'A'}
list_columns = ['Field_A']
After much digging flask-appbuilder uses it's own filterclass in order to enable you to filter your views.
All the classes are referenced here on GitHub:
Flask Filter Clases List
Also not the difference between FilterEqual and FilterEqualFunction here:
What is the difference between : FilterEqual and FilterEqualFunction?
For other customisation and first port of call of Flask-appbuilder go straight to the API Reference where you'll find a couple of examples of the filterclass in action.
In essence it is extremely simple. In your views.py code within the ModelView class you want to filter simply add base_filters = [['field_A', FilterEqual, 'abc']] like so:
`class Table_AView(ModelView):
datamodel = SQLAInterface(Table_AView)
label_columns = {'Field_A':'A'}
list_columns = ['Field_A']
base_filters = [['field_A', FilterEqual, 'abc']]`
This will only show the lines where the field_A variable is equal to abc.
Hope this helps someone as it took me nearly (sigh) two weeks to figure it out...
SQLALchemy is an ORM (Object-Relational Mapping), it mean that you dont have to deal with raw SQL, you will call a function that you "build" (by adding filters in your case). It will transparently generate an SQL query, execute it, and return the result as python objects.
I would suggest you to read closely at sqlalchemy documentation about filters again, especially filter_by :
http://docs.sqlalchemy.org/en/latest/orm/query.html#sqlalchemy.orm.query.Query.filter_by
It is the easiest way to apply a WHERE with sqlalchemy.
If you have declared correctly the model for Table_A, you should be able to use it so:
result = session.query(Table_A).filter_by(Field_A = 'some text').all()
Here session.query(Table_A).filter_by(Field_A = 'some text') will generate the SQL, and .all() will execute it.
I'm Using Excel/Access 2007. I made an Access query in Access, and I tried to import it into Excel using The Data Tab -> Get External Data Subtab -> From Access. I chose my Database, and chose the Query I wanted to import. However, only the headers of the table as well as 2 blank lines show up (as evidenced by their being formatted as a table). There is definitely data that is returned in the query, that I can verify by checking Access. Any help would be greatly appreciated
As an aside, can this be done programatically?
EDIT: Here is the SQL query in all it's glory
SELECT [Meter#], [LDC#], [ESCO#], [Brand], [LDCName], [RateClass], [RateSubClass], [CustName],
[DemandZone], [Type], dbo_Forecasts.Name AS ForecasForecastType,
Min(IntervalMeterConsumption.[DateFrom]) AS ConsumptionStart, IntermediateLog.[MaxOfDateRead] AS ConsumptionEnd,
Sum([kWh])/(Sum([Interval])/365) AS AverageAnnual
FROM (IntermediateLog
INNER JOIN (
(Premise INNER JOIN Meters ON Premise.PremiseCt = Meters.PremiseCt)
INNER JOIN IntervalMeterConsumption
ON Meters.Meterid = IntervalMeterConsumption.MeterID)
ON IntermediateLog.[LDC#] = Premise.CustomerPremiseNo)
INNER JOIN dbo_Forecasts ON Meters.ForecastID = dbo_Forecasts.ForecastID
WHERE ((([MaxOfDateRead]-[DateFrom])<=380))
GROUP BY IntermediateLog.[Meter#], IntermediateLog.[LDC#], IntermediateLog.[ESCO#],
IntermediateLog.Brand, IntermediateLog.LDCName, IntermediateLog.RateClass,
IntermediateLog.RateSubClass, IntermediateLog.CustName, IntermediateLog.DemandZone,
IntermediateLog.Type, dbo_Forecasts.Name, IntermediateLog.MaxOfDateRead;
You could try removing the where clause just temporarily to see if that makes a difference.
When you run the query in Access does it ask for a parameter?
The code to export a query to Excel from Access is as follows:
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel12, "Query/Table Name", "c:\export.xls"
thanks Mark
If I try to add a where clause, containing a lambda filter on a boolean field, to a nhibernate linq query, the filter seems to be ignored:
var result = Session.Linq().Where(x=> x.Approved);
Session is an iSession and Newspaper is a simple object with the fields NewspaperId int, Name - varchar(50) and Approved - bit.
When I run this the following sql is generated:
SELECT this_.NewspaperId as Newspape1_33_0_, this_.Name as Name33_0_, this_.Approved as Approved33_0_, FROM Newspapers this_
it seems to ignore the lambda if it is for a boolean field.
It works fine for the name field, ie:
var result = Session.Linq().Where(x=> x.Name == "The Times");
results in:
exec sp_executesql N'SELECT this_.NewspaperId as Newspape1_33_0_, this_.Name as Name33_0_, this_.Approved as Approved33_0_ FROM Newspapers this_ WHERE this_.Name = #p0',N'#p0 nvarchar(9)',#p0=N'The Times'
Anybody know why I can't query on a boolean value?
Any help is greatly appreciated
I am using NHibernate 2.1 with linq
It's been a while so you've probably got your answer somewhere else a long time ago. But to answer your question: I can't see a reason why this wouldn't work. Actually I've tried it out in both NH2.1.2 and NH3.0.0. It works in both (verified by looking at the query with SQL Profiler). So it would be interesting to see the mapping you used, perhapse there's something wrong there.