PowerBI Folding on Native Query based on AWS Athena query-incremental refresh - powerbi

I'm trying to figure out whether an AWS Athena query is successfully folding on the Native Query in PowerBI, for the purpose of setting up an incremental refresh. I created the parameters, filtered my datetime column on those parameters and tried the Diagnose tool (see https://www.youtube.com/watch?v=QEFze-LdLqo from 4:50 on), but it keeps running and doesn't show any results. So, I'm trying the approach of querying in the Advanced Editor (https://www.youtube.com/watch?v=KEh2Udm6ibA&feature=youtu.be 20:00 onwards). But since this example is in SQL and I'm working with AWS Athena, I keep getting errors. Here are the Advanced Editor queries I have tried so far:
Example 1:
> let
> Source = Odbc.Query("dsn=Simba Athena", "SELECT * FROM ""databasename"".""tablename"" where StartTimeCET>= ' " &
> DateTime.From(RangeStart) & "' and StartTimeCET< '" &
> DateTime.From(RangeEnd) & "' ") in Source
Error: We cannot apply operator & to types Text and DateTime.
Example 2:
> let
> Source= Odbc.Query("dsn=Simba Athena", "SELECT * FROM ""database"".""tablename""
> where StartTimeCET>= ' " DateTime.From(RangeStart) "' and
> StartTimeCET< '" DateTime.From(RangeEnd) "' ")
Error: Token Comma expected.
Example 3:
let
Source = Odbc.Query("dsn=Simba Athena", "SELECT * FROM ""database"".""tablename"" where StartTimeCET>= ' "" &
Text.From(RangeStart) & ""' and StartTimeCET < '"" & Text.From(RangeEnd) & "" ' ") in Source
Error: Exception parsing query SELECT * FROM ""database"".""tablename"" where StartTimeCET>= ' " & Text.From(RangeStart) & "' and StartTimeCET < '" & Text.From(RangeEnd) & " ' with parser version athena_v1 and context QueryExecutionContext(queryId=null, database=default, catalog=null) [Execution ID: ]
Any ideas on how to write such an Advanced Editor query for AWS Athena? To simplify, I want to filter the Advanced Editor query in PowerBI based on the RangeStart and RangeEnd paramaters. Both parameters and StartTimeCET column are type date/time.

I think I solved the error but still failed to "View Native Query".
You can pass the manual Athena direct query step by writing with Presto syntax and using DateTime.ToText() function with appropriate date format i.e.
Odbc.Query("dsn=Simba Athena",
"SELECT * FROM tablename
WHERE StartTimeCET >= TIMESTAMP '" & DateTime.ToText(RangeStart, "yyyy-MM-dd") & "'
AND StartTimeCET < TIMESTAMP '" & DateTime.ToText(RangeEnd, "yyyy-MM-dd") & "'
")
EDIT:
I think I have managed to achieve the "Incremental Load" in Power BI using Athena. This (still) does not allow you to view Native query but you can still make Power BI manipulate the direct query to implement it.
To avoid full scan of S3 data in Athena - you have to enable Partitions in your dataset.
Without going off topic, once you partition the S3 data via Athena you can then pin point the datasets with days/months/years without scanning your whole dataset.
Once you do that, you can achieve the Incremental Load by running Direct Queries as mentioned in the last video link you shared and achieve resource-efficient query execution.
The final query will look something like -
Odbc.Query("dsn=Simba Athena",
"SELECT * FROM tablename
WHERE year >= " & DateTime.ToText(RangeStart, "yyyy") & "
AND month >= " & DateTime.ToText(RangeStart, "MM") & "
AND day >= " & DateTime.ToText(RangeStart, "dd") & "
AND year <= " & DateTime.ToText(RangeEnd, "yyyy") & "
AND month <= " & DateTime.ToText(RangeEnd, "MM") & "
AND day <= " & DateTime.ToText(RangeEnd, "dd") & "
")
EDIT #2: OR simply
Odbc.Query("dsn=Simba Athena",
"SELECT * FROM tablename
WHERE dt >= '" & DateTime.ToText(RangeStart, "yyyy/MM/dd") & "'
AND dt <= '" & DateTime.ToText(RangeEnd, "yyyy/MM/dd") & "'
")

Related

How to setup a stored procedure with incremental dates in Power BI

I am new to Power BI. I am using an SQL stored procedure to get the data.
execute ED_DS_TRANS_DETAIL01 #DateFrom ='2022-09-20', #DateTo = '2022-09-20'
It does give me the required data but I want it to be incremental. For example, today is the 20th and tomorrow is the 21st. So I want to set up the power bi in such a way that it gets the 21st data and then the next data 22nd and so on. Also, it doesn't replace the previous date data and places the next data underneath the previous one.
I have tried the given solution
let
Source = (Query as text) => let
Source = Sql.Database("IP", "DB" , [Query=Query, CreateNavigationProperties=false])
in
Source
in
Source
let
tdy = Date.From(DateTime.LocalNow()),
yest = Date.AddDays(tdy , - 1),
sQuery = Table.FromRecords({
[sQuery = "execute ED_DS_TRANS_DETAIL01 #DateFrom ='" & Date.ToText(yest,[Format="yyyy-MM-dd"]) & "', #DateTo = '" & Date.ToText(tdy,[Format="yyyy-MM-dd"]) & "'"
]}),
#"Invoked Custom Function" = Table.AddColumn(sQuery, "Query2", each #"Fnc Query"([sQuery]))
in
#"Invoked Custom Function"
GUI
When I click "OK" button I am getting Details: "Microsoft SQL: Incorrect syntax near '='."
You can do it at the Power Query side...
First create the parameters of dBaseIP and dBase in case you may need to change it later...
Then create a custom function which will run the SQL query "New Query" → Other Sources → "Blank Query".
let
Source = (Query as text) => let
Source = Sql.Database(dBaseIP, dBase , [Query=Query, CreateNavigationProperties=false])
in
Source
in
Source
At last, create the below function which will update your query as per today's date...
let
tdy = Date.From(DateTime.LocalNow()),
yest = Date.AddDays(tdy , - 1),
sQuery = Table.FromRecords({
[sQuery = "execute ED_DS_TRANS_DETAIL01 #DateFrom ='" & Date.ToText(yest,[Format="yyyy-MM-dd"]) & "', #DateTo = '" & Date.ToText(tdy,[Format="yyyy-MM-dd"]) & "'"
]}),
#"Invoked Custom Function" = Table.AddColumn(sQuery, "Query2", each #"Fnc Query"([sQuery]))
in
#"Invoked Custom Function"
Check this sample file... Change the database IP and name and then try to run it...

SSAS Rowset Action: Replace blank value from DMVs with a text string using MDX

Working in SSAS (inside Visual Studio Shell), I have a rowset action created that returns basic measure information from $SYSTEM.MDSCHEMA_MEASURES. Not all measures in the SSAS database have descriptions.
How can I replace BLANK description values with a simple text string "No description available."
"select [MEASURE_CAPTION], [MEASUREGROUP_NAME], [MEASURE_DISPLAY_FOLDER],[DESCRIPTION], [EXPRESSION]
from $SYSTEM.MDSCHEMA_MEASURES where [MEASURE_UNIQUE_NAME] = '" + Measures].CurrentMember.UniqueName + "'AND [CUBE_NAME] = '" + [Measures].CurrentMember.Properties("CUBE_NAME") + "'"
Returns:
Current Measure Description
Distinct Person Count
DESIRED Return:
Current Measure Description
Distinct Person Count No Description Available
Rowset Action Configuration
Is that just straight sql replacement of null or is your script returning a string "BLANK" ?
Try replacing [DESCRIPTION] with:
ISNULL([DESCRIPTION],'No Description Available')
or
CASE WHEN [DESCRIPTION] = 'BLANK' THEN 'No Description Available' ELSE [DESCRIPTION] END

SQL Query with variables

Im trying to insert values into a mysql database:
database->queryDatabase("INSERT INTO recordings (title, recording, kit, date) VALUES ('"+recordingTitle+"', '"+ recordingArray +"', '"+kitID+"', '"+recordingDateTime+"')");
database->queryDatabase just sends it to my database connection.
The problem I am having is that:
error: no match for 'operator+' in 'operator+(const QString&, const char*)(((const char*)"\', \'")) + ((Studio*)this)->Studio::recordingDateTime
Each var is of type:
QString recordingTitle;
std::vector<std::pair<int, QString> > recordingArray;
int kitID;
QDateTime recordingDateTime;
How can I add each one to the database? The vector and QDateTime types do not like the + in the query string.
Tahnks
There's no implicit conversion of QDateTime to QString. You'll need to explicitly convert it:
database->queryDatabase("INSERT INTO recordings (title, recording, kit, date)"
" VALUES ('" + recordingTitle + "', '" + recordingArray +"', '" + kitID +
"', '" + recordingDateTime.toString() + "')");
You might have to provide a format specifier to get it into a format MySQL likes.
Please also remember that concatenating for SQL queries is not a good idea, unless you know exactly what you are doing, since it enables SQL-Injection attacks. You should use the bindValue method. This also has the side effect that you query will become faster and also most likely solve the original problem.

problems with django raw query parameters

I was trying to make a custom raw query for a model and i get this error:
DatabaseError: error de sintaxis en o cerca de
«E'positions_statusrecord'» LINE 1: SELECT id FROM
E'positions_statusrecord' WHERE "type"=E'Leav...
Here is the raw query i'm trying to use (it's a manager method):
def get_status_ids(self, model):
"""
This query returns the latest statuses ids for each entry
of "model" in StatusRecord.
"""
db_table = self.model._meta.db_table
model_type = model.get_status_type()
raw_query = (
"SELECT id "
"FROM %s "
"WHERE \"type\"=%s AND "
"(identifier,date_time) IN "
"( "
"SELECT identifier, Max(date_time) "
"FROM %s "
"WHERE \"type\"=%s "
"GROUP BY identifier"
")"
)
params = (db_table, model_type, db_table, model_type, )
return self.raw(raw_query, params)
I've tried with a simpler query (just a SELECT ... FROM ..) and had the same problem. It seems to be that raw queries couldn't have the FROM part completed with a parameter.
Am i right? or have i made a mistake and i'm not finding it?
I'm using postgreSQL 8.4.10, django 1.3 and python 2.6.
I've searched information about raw queries parameters to see if there are some forbidden formatting options, but i didn't find anything that helps me.
Does anyone knows what's causing this error?
It seems to be that raw queries couldn't have the "FROM" part completed with a parameter.
Yes, the ORM will quote the string argument making it ... FROM 'some_table' ....
Since the db_table parameter is trusted (not originated from user input), you can do something like:
raw_query = (
"SELECT id "
"FROM %s "
"WHERE \"type\"=%%s AND "
"(identifier,date_time) IN "
"( "
"SELECT identifier, Max(date_time) "
"FROM %s "
"WHERE \"type\"=%%s "
"GROUP BY identifier"
")"
) % (db_table, db_table)
return self.raw(raw_query, (model_type, model_type))
Since Django Aggregation can be used in filters, probably you can get the same results without resorting to raw SQL (look also the in lookup example).
Look if you can replace raw() with QuerySet.extra() and SQL IN with EXISTS.

Qt Query Top Number Record Selecting

I have a query that should request the top X number of records using the Qt framework to actually make the request to the SQL database. I have verified when I place an hard-coded number the query is successful, but when I attempt to bind to it I get an error.
query.prepare("SELECT TOP :numberToSelect"
" deviceId"
" , latitude"
" , longitude"
" , [timeStamp]"
" FROM Positions "
" WHERE [address] = ''"
" ORDER BY [timeStamp] DESC");
query.bindValue(":numberToSelect", numberMissing);
The variable numberMissing is an unsigned short which is passed in. Upon execution I receive this error:
Unable to execute statement: "[Microsoft][ODBC SQL Server Driver][SQL
Server]Incorrect syntax near '#P1'. [Microsoft][ODBC SQL Server
Driver][SQL Server]Statement(s) could not be prepared. QODBC3: Unable
to execute statement" "SELECT TOP ? deviceId , latitude ,
longitude , [timeStamp] FROM Positions WHERE [address] = ''
ORDER BY [timeStamp] DESC"
I do not see what the error would be.
Oracle parameters are signified with a preceding : - SQLServer's closest equivalent would be an # sign. Try changing :numberToSelect to #numberToSelect.
When you do a select top with a variable, the top value needs to be in parenthesis.
Try this:
query.prepare("SELECT TOP (:numberToSelect)"
" deviceId"