Meta programing of DolphinDB: how to pass a function in sqlCol - sql

I’m trying something with the function sqlUpdate and the where condition that I passed in is generated with the metaprogramming technique. I got an error:
::evaluate(sqlUpdate(t1, u, , w)) => Unrecognized column name date(date)
Here’s my full script:
t1=table(`A`A`B`B as symbol, 2021.04.15 2021.04.16 2021.04.15 2021.04.16 as date, 12 13 21 22 as price)
updCol = `price
dateCol = `date
u = sqlColAlias( expr(sqlCol(updCol), +, -1) , updCol )
w = expr(sqlCol("date("+dateCol+")"), ==, 2021.04.15)
sqlUpdate(table=t1 ,updates=u ,where = w).eval()
What is the problem here?

If you execute sqlCol("date("+dateCol+")") independently, the result is:
< date(date) >
It may seem correct at first glance. However, as the first argument of sqlCol is a column, the whole thing date(date) will be parsed as a column name.
Remember that the second argument of sqlCol is a function. So we can write sqlCol(dateCol,date). In this way, “date“ will be recognized as a column name and the second argument is treated as the function to be applied to the “date“ column.
The parsing result:
< date(date) as date >
Full script:
t1=table(`A`A`B`B as symbol, 2021.04.15 2021.04.16 2021.04.15 2021.04.16 as date, 12 13 21 22 as price)
updCol = `price
dateCol = `date
u = sqlColAlias( expr(sqlCol(updCol), +, -1) , updCol )
w = expr(sqlCol(dateCol, date), ==, 2021.04.15)
sqlUpdate(table=t1 ,updates=u ,where = w).eval()

Related

multiple conditions in oracle case with one :PAR

I have a more complex query, but I will give a simple example. In SSRS same input but need different outputs:
select * from myTable where
case
when :PAR1 = 'hour' then myTable.hour = :PAR1
when :PAR1 = 'Mounth' then myTable.Mounth = :PAR1
end
How to make it?
I'm try to
case length(:PAR1)
when 18 then hour: = PAR1
..
always a mistake..
You don't need a CASE expression here:
SELECT *
FROM myTable
WHERE (:PAR1 = 'hour' AND hour = :PAR1) OR
(:PAR1 = 'Mounth' AND Mounth = :PAR1);
Code you posted doesn't make sense to me; are you sure that :PAR1 is used everywhere? I'd expect something like this instead
select *
from mytable
where (:PAR1 = 'hour' and hour = :PAR2)
or (:PAR1 = 'Mounth' and mounth = :PAR2)
-------
maybe not :PAR2, but
certainly not :PAR1
Also, when you're dealing with hours, what is mounth? Shouldn't that be month?

Spark SQL is interpreting a datetime.date object as a mathematical formula or integer in statement

I've encountered a problem in Spark SQL. It is interpreting a datetime.date object as a mathematical formula, or integer, in a SQL statement I am writing.
currentDateAndTime = datetime,now()
current_month = currentDateAndTie.strftime("%m")
current_year = currentDateAndTime.strftime("%Y")
first_day_of_month = date(int(current_year), int(current)month), 1)
print(first_day_of_month)
type(first_day_of_month)
and you get:
2022-10-01
datetime.date
Then when I do
df = spark.sql("""
SELECT * FROM table_A
WHERE IncidentCreatedDate < {}
""".format(first_day_of_month))
I get an error that says AnalysisException: cannot resolve '(table_A.IncidentCreatedDate < ((2022 - 10) - 1' due to data type mismatch: differing types in '(tableA.IncidentCreatedDate < ((2022 - 10 - 1))' (date and int).;......
There might be a typo in everything above because I had to type everything out on another laptop since the other one is my work laptop and they don't like me sending anything from that laptop to anywhere else.)
pyspark doesn't support prepared statements.
format will replace the pace holder, but strings mus be in single quotes, so simply add them
df = spark.sql("""
SELECT * FROM table_A
WHERE IncidentCreatedDate < '{}'
""".format(first_day_of_month))

LINQ query where column contains a specific number >= specific value you want to query

I have a table named SubcodeTable and I want to query in SubsidiaryCode where first 3characters is >= to 21Y
Query in table where a column contains >= '21Y'
SubcodeTable:
Column1 Column2
SubsidiaryCode Desc
18Y-001 AAA
19Y-001 AAA
20Y-001 AAA
21Y-001 CCC
22Y-003 EEE
23Y-001 FF
So output should display:
Column1 Column2
SubsidiaryCode Desc
21Y-001 CCC
22Y-003 EEE
23Y-001 FF
By the way first 3 characters of SubsidiaryCode represent year like 21Y=2021.
I manage to create a SQL query, so how do to it in LINQ query ?
SQL query:
SELECT LEN (Whh_SubsidiaryCode) [StringLength],LEFT(Whh_SubsidiaryCode,2)[FirsttwoCharInSubCode]
,Whd_WHNo [RR NUMBER], Whh_SubsidiaryCode [SubsidiaryCode], Whd_WHSeqNo [SEQ], Whd_WHSplitSeqNo [SPLIT SEQ] ,Whd_WHIssuedQty [QTY],Saw_StockName [ITEM NAME],Saw_StockSpecs1 [ASSET DESCRIPTION]
FROM E_WHDetailEntry
JOIN E_WHHeaderEntry ON Whd_WHNo=Whh_WHNo
JOIN E_StockAndWorkMaster ON Whd_StockCode=Saw_StockCode
WHERE Whd_StockType='FS2'
AND Whh_SubsidiaryCode LIKE '%Y%' AND LEFT(Whh_SubsidiaryCode,2) >= '21'
ORDER BY Whh_SubsidiaryCode
So this is my LINQ query, I tried to use y.Whh_SubsidiaryCode.Substring(0,2) >'20' but it says Too many characters in car literal & operator > cannot be applied to operands of type string and char.
private List<string> GetBudgetCodes()
{
using (var ctx = LinqExtensions.GetDataContext<NXpert.FixedAsset.DataAccess.FixedAssetDataContext>("AccountingDB"))
{
var list = (from x in ctx.DataContext.E_WHDetailEntries
join y in ctx.DataContext.E_WHHeaderEntries
on x.Whd_WHNo equals y.Whh_WHNo
where x.Whd_StockType == "FS2"
&& y.Whh_SubsidiaryCode.Contains("y")
&& y.Whh_SubsidiaryCode.Substring(0,2) >= '21'
select new { y.Whh_SubsidiaryCode }
).DistinctBy(y => y.Whh_SubsidiaryCode).OrderBy(y => y.Whh_SubsidiaryCode).ToList();
var budgetcode = list.Select(y => y.Whh_SubsidiaryCode.Trim()).ToList();
return budgetcode;
}
}
As it says in exception
> cannot be applied to operands of type string and char.
You need to parse Whh_SubsidiaryCode first to be able to compare values.
So this
&& y.Whh_SubsidiaryCode.Substring(0,2) >= '21'
should be like this:
&& Convert.ToInt32(y.Whh_SubsidiaryCode.Substring(0,2)) > 21
y.Whh_SubsidiaryCode.Substring(0,2) >'20' but it says
Too many characters in char literal
Indeed; you can only put one character inside ' in C#. If you want to put more than one character, you need a string, which is delimited by "
Operator > cannot be applied to operands of type string and char
> as a maths operation doesn't work with a string on one side and a char on the other. You can use it on two chars, or on two strings, but not on a mix
'a' > 'b' //false
"a" > "b" //false
"a" > "A" //true - a is ASCII 97, A is ASCII 65. 97 is greater than 65
I'd say you can simply use:
y.Whh_SubsidiaryCode >= "21Y"
if your code is always number number Y, but you should be aware that this is an alphameric comparison. It'll work fine for any other code that is also number number Y. Critically, a string of 100Y is not greater than 21Y because the first character, 1 is not greater than 2
Unless you have other codes like 21X, you can dump the LIKE '%Y%' / Contains("y") - that just slows things down
I finally gotten a solution in SQL.
by using LEN then get the length then using LEFT to get the first 2 char.
Then create a where clause for the condition:
LEFT(Whh_SubsidiaryCode,2) >= '20'
SELECT LEN (Whh_SubsidiaryCode) [StringLength],LEFT(Whh_SubsidiaryCode,2)[FirsttwoCharInSubCode]
,Whd_WHNo [RR NUMBER], Whh_SubsidiaryCode [SubsidiaryCode], Whd_WHSeqNo [SEQ], Whd_WHSplitSeqNo [SPLIT SEQ] ,Whd_WHIssuedQty [QTY],Saw_StockName [ITEM NAME],Saw_StockSpecs1 [ASSET DESCRIPTION]
FROM E_WHDetailEntry
JOIN E_WHHeaderEntry ON Whd_WHNo=Whh_WHNo
JOIN E_StockAndWorkMaster ON Whd_StockCode=Saw_StockCode
WHERE Whd_StockType='FS2'
AND Whh_SubsidiaryCode LIKE '%Y%' AND LEFT(Whh_SubsidiaryCode,2) >= '20'
ORDER BY Whh_SubsidiaryCode
Thanks for the help guys.
About the LINQ I manage to query the results using List, create a function that returns the met condition.
Code:
private static bool CodeFiltered(string code)
{
return ((Convert.ToInt32(code.Substring(0,2)) >= 20));
}
var lstBudgetCodes = GetBudgetCodes();
List<string> ResultCode =new List<string>(lstBudgetCodes.FindAll(CodeFiltered));

What is the syntax problem here using this subquery inside where clause

SELECT p.pnum, p.pname
FROM professor p, class c
WHERE p.pnum = c.pnum AND c.cnum = CS245 AND (SELECT COUNT(*) FROM (SELECT MAX(m.grade), MAX(m.grade) - MIN(m.grade) AS diff
FROM mark m WHERE m.cnum = c.cnum AND m.term = c.term AND m.section = c.section AND diff <= 20)) = 3
Incorrect syntax near ')'. Expecting AS, FOR_PATH, ID, or QUOTED_ID.
Consider the following example:
SELECT COUNT(1)
FROM SYSCAT.TABLES T
WHERE
(
-- SELECT COUNT(1)
-- FROM
-- (
SELECT COUNT(1)
FROM SYSCAT.COLUMNS C
WHERE C.TABSCHEMA=T.TABSCHEMA AND C.TABNAME=T.TABNAME
-- )
) > 50;
The query above works as is. But the problem is, that if you uncomment the commented out lines, you get the following error message: "T.TABNAME" is an undefined name. and least in Db2 for Linux, Unix and Windows.
You can't push external to the sub-select column references too deeply.
So, your query is incorrect.
It's hard to correct it, until you provide the task description with data sample and the result expected.
I can see a potential syntax errors: It seems that CS245 refers to a value c.cnum may take and not a column name. If that is the case, it should be enclosed in single quotes.

How do I pass a parameter in Report Builder to Firebird database?

I'm looking at doing some report development for one of our Training softwares. I finally got some queries working in FB Maestro, as I'm only familiar with SQL and Oracle.
I have the following query that works and returns results, but when trying to set up a parameter for the display name, the query runs (at least it returns no errors) however the dataset does not return any data. Has anyone worked with these before?
Here's the query:
Select CertStatus, DisplayName, Count(CertStatus) From ( With cte as (Select * From (Select COURSEVERSIONSWITHAGGREGATES.CourseTitle, COURSEVERSIONSWITHAGGREGATES.CourseNumber, "MaxTrainedCompletionDate", "Course_ID", PersonnelView.DISPLAYNAME, COURSEVERSIONSWITHAGGREGATES.RecertificationValue, COURSEVERSIONSWITHAGGREGATES.RECERTIFICATIONUNIT_ID,
CASE
WHEN COURSEVERSIONSWITHAGGREGATES.RECERTIFICATIONUNIT_ID = 3 THEN DATEADD(year, 1*COURSEVERSIONSWITHAGGREGATES.RECERTIFICATIONVALUE, MaxTrainingView."MaxTrainedCompletionDate")
WHEN COURSEVERSIONSWITHAGGREGATES.RECERTIFICATIONUNIT_ID = 2 THEN DATEADD(month, 1*COURSEVERSIONSWITHAGGREGATES.RECERTIFICATIONVALUE, MaxTrainingView."MaxTrainedCompletionDate")
WHEN COURSEVERSIONSWITHAGGREGATES.RECERTIFICATIONUNIT_ID = 1 THEN DATEADD(week, 1*COURSEVERSIONSWITHAGGREGATES.RECERTIFICATIONVALUE, MaxTrainingView."MaxTrainedCompletionDate")
WHEN COURSEVERSIONSWITHAGGREGATES.RECERTIFICATIONUNIT_ID = 0 THEN DATEADD(day, 1*COURSEVERSIONSWITHAGGREGATES.RECERTIFICATIONVALUE, MaxTrainingView."MaxTrainedCompletionDate") END
AS ExpirationDate
From MAXTRAININGVIEW
INNER JOIN PERSONNELVIEW ON (MAXTRAININGVIEW."Personnel_ID" = PERSONNELVIEW.PERSONNELID) INNER JOIN COURSEVERSIONSWITHAGGREGATES ON (MAXTRAININGVIEW."Course_ID" = COURSEVERSIONSWITHAGGREGATES.COURSEID)
WHERE Personnelview.DisplayName = 'Aaron')) Select CourseTitle, CourseNumber, "MaxTrainedCompletionDate", "Course_ID", DisplayName, RecertificationValue, Recertificationunit_ID, ExpirationDate,
CASE WHEN ExpirationDate > current_date Then 'Active' WHEN ExpirationDate < current_date Then 'Expired' END As CertStatus from cte) Group By CertStatus, DisplayName
This returns values with the static value of 'Aaron' in report builder. But trying to use a parameter, it does not throw an error in report builder, however it just does not return any data.
For example this:
WHERE Personnelview.DisplayName = '#DisplayName'))
I've got the parameter based off another data set query, and that seems to work (it gives me the option to select employees)
Here is an example of it passing 'Aaron' (with personal info removed)
Example of passing #FName Parameter:
If you want to pass the parameter in report, other type database might not recognize query like "where [field] in #parameter", so I think you could try to use filter to achieve this goal(create a filter in dataset, and create a parameter, then specify it in filter properties).