How to change filter in date parameter to range in Looker - looker

I am trying to see if there is a way to have the filter on a date parameter be a date range instead of a single date value. Does anyone have any creative ideas on how to do this.

You probably want to replace your parameter with a templated filter. See the docs for more info, but in short:
In situations where you want to offer users more flexible input (such as with various kinds of date ranges or string searches), try to use templated filters when possible.
Your code will look something like this:
view: customer_facts {
derived_table: {
sql:
SELECT
customer_id,
SUM(sale_price) AS lifetime_spend
FROM
order
WHERE
{% condition order_date %} order.dt {% endcondition %}
GROUP BY 1
;;
}
dimension: order_date {
type: date
sql: ${TABLE}.dt ;;
}

Related

Is there a way to INSERT Null value as a parameter using FireDAC?

I want to leave some fields empty (i.e. Null) when I insert values into table. I don't see why would I want to have a DB full of empty strings in fields.
I use Delphi 10, FireDAC and local SQLite DB.
Edit: Provided code is just an example. In my application values are provided by user input and functions, any many of them are optional. If value is empty, I would like to keep it at Null or default value. Creating multiple variants of ExecSQL and nesting If statements isn't an option too - there are too many optional fields (18, to be exact).
Test table:
CREATE TABLE "Clients" (
"Name" TEXT,
"Notes" TEXT
);
This is how I tried it:
var someName,someNote: string;
begin
{...}
someName:='Vasya';
someNote:='';
FDConnection1.ExecSQL('INSERT OR REPLACE INTO Clients(Name,Notes) VALUES (:nameval,:notesval)',
[someName, IfThen(someNote.isEmpty, Null, somenote)]);
This raises an exception:
could not convert variant of type (Null) into type (OleStr)
I've tried to overload it and specify [ftString,ftString] and it didn't help.
Currently I have to do it like this and I hate this messy code:
FDConnection1.ExecSQL('INSERT OR REPLACE INTO Clients(Name,Notes) VALUES ('+
IfThen(someName.isEmpty,'NULL','"'+Sanitize(someName)+'"')+','+
IfThen(someNote.isEmpty,'NULL','"'+Sanitize(someNote)+'"')+');');
Any recommendations?
Edit2: Currently I see an option of creating new row with "INSERT OR REPLACE" and then use multiple UPDATEs in a row for each non-empty value. But this looks direly ineffective. Like this:
FDConnection1.ExecSQL('INSERT OR REPLACE INTO Clients(Name) VALUES (:nameval)',[SomeName]);
id := FDConnection1.ExecSQLScalar('SELECT FROM Clients VALUES id WHERE Name=:nameval',[SomeName]);
if not SomeString.isEmpty then
FDConnection1.ExecSQL('UPDATE Clients SET Notes=:noteval WHERE id=:idval)',[SomeNote,id]);
According to Embarcadero documentation ( here ):
To set the parameter value to Null, specify the parameter data type,
then call the Clear method:
with FDQuery1.ParamByName('name') do begin
DataType := ftString;
Clear;
end;
FDQuery1.ExecSQL;
So, you have to use FDQuery to insert Null values, I suppose. Something like this:
//Assign FDConnection1 to FDQuery1's Connection property
FDQuery1.SQL.Text := 'INSERT OR REPLACE INTO Clients(Name,Notes) VALUES (:nameval,:notesval)';
with FDQuery1.ParamByName('nameval') do
begin
DataType := ftString;
Value := someName;
end;
with FDQuery1.ParamByName('notesval') do
begin
DataType := ftString;
if someNote.IsEmpty then
Clear;
else
Value := someNote;
end;
if not FDConnection1.Connected then
FDConnection.Open;
FDQuery1.ExecSql;
It's not very good idea to execute query as String without parameters because this code is vulnerable to SQL injections.
Some sources tells that it's not enough and you should do something like this:
with FDQuery1.ParamByName('name') do begin
DataType := ftString;
AsString := '';
Clear;
end;
FDQuery1.ExecSQL;
but I can't confirm it. You can try it if main example won't work.

Symfony order by the content of a specific field

I want to sort data in repository based on the content of a specific field
For example i have an entity person with the fields role,fistName and lastName.
I would like to sort using ->orderBy('p.role', ???) and get a list ordered based on this order : professors then directors then teachers and at last students .
Example of my database:
Wanted result:
Ps: i can not use ASC or DESC since my sorting order is neither ASC nor DESC;
it is a custom order
Very strage scenario, you could use a CASE statement in order to assing a custom value for each fields then sort on him.
You could use the HIDDEN keyword.
As example take a look at this DQL:
SELECT p, CASE
WHEN p.role = "professor" THEN 1
WHEN p.role = "director" THEN 2
WHEN p.role = "teacher" THEN 3
WHEN p.role = "student" THEN 4
ELSE 99 END
AS HIDDEN mySortRule
FROM Bundle\Entity\Person p
ORDER BY mySortRule ASC
Hope this help

Modify query string on a form to add filter based on other fields

I have an enquiry form which works from a view with a custom query. The form has filters, which I use in the executeQuery method of the view on the form to add ranges on various fields.
A new requirement is to filter based on two fields in the query.
Example: The PurchLine table is one of the tables in the query.
A new range is needed :
if PurchLine.ItemId != “” then
filter by PurchLine.PurchStatus == None
but, if the Item has a SPECIFIC value,
then filter by PurchStatus == Received.
(Ok, this is just an example!).
I am unable to modify my query to add a range on the PurchStatus based on the Item field.
I know exactly how the string value of the query must look, but how can I modify the query string?
The current query string looks like this (if I breakpoint on super in executeQuery):
SELECT FIRSTFAST * FROM OpenPOLinesView(OpenPOLinesView) WHERE ((CreatedDateTime<='2016-11-30T23:59:59')) AND ((VendAccount = N'S000001048'))
I want to add this at the end:
AND (((ItemId = N'') AND (PurchStatus = 0)) OR ((ItemId = N'XXX123') AND (PurchStatus = 2)))
How can I modify the query string in code?
You can use query expression for this, e.g.
queryBuildRange.value(strFmt('((%1 == %2) || ((%1 == %3) && (%4 == "%5")))',
fieldStr(InventTable, ItemType),
any2int(ItemType::Service),
any2int(ItemType::Item),
fieldStr(InventTable, ProjCategoryId),
queryValue("Spares")));
Please refer to this link Using Expressions in Query Ranges [AX 2012] for details.

How can I calculate a field based on fields in other tables while inserting a record (in a procedure)

I'm sorry for the confusing title, but couldn't find another way to ask it.
Let's say I want to write a procedure add_salesline. I enter all the fields with parameters, except subtotal. Subtotal (just the price for the salesline) needs to be calculated based on fields in other tables such as productprice in the table products, pricereduction in the table promotion, etc. (based on the properties).
How can I do this? I've been trying to solve this problem for a good week now, and it's just not working...
Presumably one of the parameters passed to procedure add_salesline() is productid, or whatever. So you use that to SELECT products.productprice, promotion.pricereduction and whatever else you need to perform the calculation.
The purpose of writing a stored procedure is to associate several calls into a single program unit. So add_salesline() might look something like this (lots of caveats because your question is very light on details):
create or replace procedure add_salesline(
p_orderno in salesline.orderno%type
, p_salesqty in salesline.salesqty%type
, p_productid in products.productid%type
)
is
new_rec salesline%rowtype;
begin
new_rec.orderno := p_orderno;
new_rec.salesqty := p_salesqty;
new_rec.productid := p_productid;
select p_salesqty * (p.productprice * nvl(pp.pricereduction, 1))
into new_rec.subtotal
from products p
left outer join promotion pp
on pp.productid = p.productid
where p.productid = p_productid
;
insert into salesline
value new_rec;
end;
This code assumes pricereduction is a rate. If the value is an absolute discount the formula will be different (p.productprice - nvl(pp.pricereduction, 0)). Or if it's a replacement price: coalesce(pp.pricereduction, p.productprice).

How to retrieve a value of an attribute from the XML stored across multiple rows using Oracle-Xquery?

We are using Oracle 11g database with XMLDB installation. We are having table with XMLType columns. The structure of the XML will be same for all the rows in a table. The table will have other fiedls also.
Now I want to retrieve only the values of the particular node's attribute values from all the rows as a string with some other relational fields. The table columns retrieved can be like TemplateId, TemplateVid,TemplatepartId.
The structure of the XML can be as follows:
<Template ID=1000 VID=1>
<TemplateParts>
<Template ID="4000" VID="1"/>
<Template ID="4001" VID="1"/>
</TemplateParts>
</Template>
So the table will have data for Template with TemplateId,Vid and TemplateXML. The TemplateXML field is an XMLType field. Now I want to retrieve all the TemplateId,Vid and its refereced template partIds as an XML table. The output should be as follows:
TemplateId - TemplateVid - TemplatePartId - TemplatepartVid
1000 1 4000 1
1000 1 4001 1
So anybody comes up with a correct Xquery for the above requirement.
Your requirement is not clear but to start you off and hopefully get you some additional comment from the wider XQuery community on StackOverflow here is a quick example. Hope this helps :)
xquery version "1.0";
<html>
<head>
<title>Sample</title>
</head>
<body>
<div align="center">
<table>
<tr><th>TemplateId</th><th>TemplateVid</th><th>TemplatePartId</th><th>TemplatepartVid</th></tr>
{
let $sample as element()* := (<root><Template ID="1000" VID="1"><TemplateParts><Template ID="4000" VID="1" /><Template ID="4001" VID="1" /></TemplateParts></Template></root>)
for $e in $sample/Template
return
for $tp in $e/TemplateParts/Template
return
(<tr><td>{data($e/#ID)}</td><td>{data($e/#VID)}</td><td>{data($tp/#ID)}</td><td>{data($tp/#VID)}</td></tr>)
}
</table>
</div>
</body>
</html>
As I have mentioned in my earlier comment, I have managed to get the IDs and VIDs which is stored under the Node /Template/TemplateParts/Template from xmltype column of all the rows. The query is as follows:
select distinct x.value as TemplatePartId,Y.Value as Vid from
TempVersion t ,
xmltable('/Template/TemplateParts/Template' passing t.CONTENT columns value varchar2(10) path '#ID' ) x,
xmltable('/Template/TemplateParts/Template' passing t.CONTENT columns value varchar2(10) path '#VID' ) y
order by TemplatePartId;
If sombody know better format,please post your sample query. I need as a normal query as the above format is not supported by my ORM tool. If you look at the above query you can notice that the XMLTable expression is to be placed after the From clause. This gives trouble when I try to form this query through my LLBLGen ORM tool.

Resources