How do I get unique values of one column based on another column using the insert database query in Anylogic? - anylogic

How do I get unique values of one column based on another column using the query?
I tried using
(double)selectFrom(tasks).where(tasks.tasks_type.eq()).uniqueResult(tasks.task_cycle_time_hr);
I want to automate this and make sure that all the values of task_type are being read and a unique value for each of the tasks_type is being returned!
For all the values in the column task_type, I require a unique value from the column task_cycle_time_hr.

I don't really understand why you're trying to do this in one query.
If you want to get the cycle time (task_cycle_time_hr column) for each task type (tasks_type column), just do queries in a loop for each possible tasks_type value. If you don't know those a priori, do queries for each value returned by a query of the task type values, which would look something like
for (String taskType : selectFrom(tasks).list(tasks.tasks_type)) {
double cycleTime = (double) selectFrom(tasks)
.where(db_table.tasks_type.eq(taskType))
.firstResult(tasks.task_cycle_time_hr);
traceln("Task type " + taskType + ", cycle time " + cycleTime);
}
But this just amounts to querying all rows and reading the task type and cycle time values from each, so you wouldn't normally do it like this: you'd just have a single query looping through all the full rows instead...
List<Tuple> rows = selectFrom(tasks).list();
for (Tuple row : rows) {
traceln("Task type " +
row.get(tasks.tasks_type) + ", cycle time " +
row.get(tasks.task_cycle_time_hr));
}
NB: I assume you don't have any rows with duplicate task types because then the whole exercise doesn't make sense unless you want only the first row for each task type value, or want some kind of aggregate (e.g., sum) of the cycle time values for each given task type. You were trying to use uniqueResult, which may mean you want to get a value if there is exactly one row (for a given task type) and 'no result otherwise', but uniqueResult throws an exception (errors) if there isn't exactly one row (so you can't use that directly like that). In that case one way (there are others, some probably slightly better) would be to do a count first to check; e.g. something like
for (String taskType : selectFrom(tasks).list(tasks.tasks_type)) {
int rowCount = (int) selectFrom(tasks)
.where(db_table.task.eq(taskType))
.count();
if (rowCount == 1) {
double cycleTime = (double) selectFrom(tasks)
.where(db_table.tasks_type.eq(taskType))
.firstResult(tasks.task_cycle_time_hr);
traceln("Task type " + taskType + ", unique cycle time " + cycleTime);
}
}

Import your excel sheet into the AnyLogi internal DB and then make use of the DB wizard that will take you step by step to write the code to retrieve the data you want
(double) selectFrom(data)
.where(data.tasks.eq("T1"))
.firstResult(data.task_cycle_time_hr)

Related

Is there a way to expand dynamically tables found in multiple columns using Power Query?

I have used the List.Accumulate() to merge mutliple tables. This is the output I've got in this simple example:
Now, I need a solution to expand all these with a formula, because in real - world I need to merge multiple tables that keep increasing in number (think Eurostat tables, for instance), and modifying the code manually wastes much time in these situations.
I have been trying to solve it, but it seems to me that the complexity of syntax easily becomes the major limitation here. For instance, If I make a new step where I nest in another List.Accumulate() the Table.ExpandTableColumns(), I need to pass inside a column name of an inner table, as a text. Fine, but to drill it down actually, I first need to pass a current column name in [] in each iteration - for instance, Column 1 - and it triggers an error if I store column names to a list because these are between "". I also experimented with TransformColumns() but didn't work either.
Does anyone know how to solve this problem whatever the approach?
See https://blog.crossjoin.co.uk/2014/05/21/expanding-all-columns-in-a-table-in-power-query/
which boils down to this function
let Source = (TableToExpand as table, optional ColumnNumber as number) =>
//https://blog.crossjoin.co.uk/2014/05/21/expanding-all-columns-in-a-table-in-power-query/
let ActualColumnNumber = if (ColumnNumber=null) then 0 else ColumnNumber,
ColumnName = Table.ColumnNames(TableToExpand){ActualColumnNumber},
ColumnContents = Table.Column(TableToExpand, ColumnName),
ColumnsToExpand = List.Distinct(List.Combine(List.Transform(ColumnContents, each if _ is table then Table.ColumnNames(_) else {}))),
NewColumnNames = List.Transform(ColumnsToExpand, each ColumnName & "." & _),
CanExpandCurrentColumn = List.Count(ColumnsToExpand)>0,
ExpandedTable = if CanExpandCurrentColumn then Table.ExpandTableColumn(TableToExpand, ColumnName, ColumnsToExpand, NewColumnNames) else TableToExpand,
NextColumnNumber = if CanExpandCurrentColumn then ActualColumnNumber else ActualColumnNumber+1,
OutputTable = if NextColumnNumber>(Table.ColumnCount(ExpandedTable)-1) then ExpandedTable else ExpandAll(ExpandedTable, NextColumnNumber)
in OutputTable
in Source
alternatively, unpivot all the table columns to get one column, then expand that value column
ColumnsToExpand = List.Distinct(List.Combine(List.Transform(Table.Column(#"PriorStepNameHere", "ValueColumnNameHere"), each if _ is table then Table.ColumnNames(_) else {}))),
#"Expanded ColumnNameHere" = Table.ExpandTableColumn(#"PriorStepNameHere", "ValueColumnNameHere",ColumnsToExpand ,ColumnsToExpand ),

Searching a column in Entity Framework with multiple values

I am trying to run a search on one particular field of a table with a list of values. Not able to find a solution so far. Any help is really appreciated.
Here is the scenario
var records = new PagedList<Required>();
var result = db.Required.Where(x => filter == null || (x.Title.Contains(filter)) || x.CID.Contains(filter));
foreach (string str in SelectedNetwork)
{
string tempStr = str;
result = result.Where(x => x.Network == tempStr);
records.TotalRecords = result.Count();
}
records.Content = result
.Where(x => filter == null ||
(x.Title.Contains(filter))
|| x.CID.Contains(filter)
)
.OrderBy(sort + " " + sortdir)
.Skip((page - 1) * Convert.ToInt32(records.PageSize))
.Take(Convert.ToInt32(records.PageSize))
.ToList();
highlighted code in the foreach loop fails to run as per expectation. Is there any way, I can fix it?
Thanks
Tutumon
You must take into account that LINQ expressions are queries, until you materialize them. To materialize them you need to either enumerate them, or convert them to a list, array, or whatever, i.e. enumerate their members in a foreach, or call a method like ToList(), or ToArray().
In your code the original query stored in result is not materialized, so everytime a foreach loop is executed, a new Where contidion is added to the original query. To vaoid this behavior you need to recreate the whole results query in each iteration, so that you get a fresh copy of the unfilterd expression.
There would be another solution which would be to materialize the result query and then run the foreach loop as is. The problem of this solution would be that you would get all the data from the database, keep it in memory and run the Where and the Count on the in-memory copy. Unless there is a very small number of rows in Required that would be a very bad idea.

Distinct MondoDB function - How to use some criteria with distinct

I have a situation where I need fetch only distict records which are grater than 0 and all records with value 0.
For Example I have column name called mid then it rows like "0,0,1,1,2,3,5,5,3" then I should fetch only "0,0,1,2,5,3".
In short distinct record plus all mid with value 0
I have used this
def distinctMIdCursor = dataSetCollection.distinct("mid",whereObject)
def distinctMIdList = distinctMIdCursor.asList()
but its fetching result like "0,1,2,5,3"
Actual result "0,1,2,5,3".
Expected result "0,0,1,2,5,3"
How to achieve it. What is better way?
You cannot achieve it with distinct because by doing so you are defying the whole purpose of using distinct. Instead you can write two queries and concat the result.
def nonZeroDistinctList = dataSetCollection.distinct("mid",{mid: {$ne:0}});
// map function to convert object list into mid value list
def allZeroList = dataSetCollection.find({mid:0}).map(function(doc){return doc.mid});
// concating the two lists
def result = nonZeroDistinctList + allZeroList ;

Firebird 2.5.x. Extract column names and column datatypes of a result from stored procedure

I have a Firebird 2.5 database .As an example I have stored procedure with a name QRESULT which expected return is:
Parameter - DATATYPE
a - date
b - numeric(18,0)
c - integer
d - varchar(50)
and so on....
I use PHP - PDO to query the firebird database using the procedure QRESULT like this:
SELECT a,b,d from QRESULT() where a = "some value"
I need to run some query before QRESULT procedure and i need it to return the datatype of all the columns that QRESULT would return if it was ran. So i can help user to type proper value for my "where" clause.I know i can set that manually in the user interface, but in the real project there are lots of procedures and if there is a way i can make my filter interface generate dynamically i would be happy about that.If this is not possible for a stored procedure i can make it with select statements.I just need some lead.
The information you want is in the RDB$PROCEDURE_PARAMETERS table, basically what you need is query
SELECT r.RDB$PARAMETER_NAME ParName, F.RDB$FIELD_TYPE ParType
FROM RDB$PROCEDURE_PARAMETERS r
JOIN RDB$FIELDS F ON(F.RDB$FIELD_NAME = R.RDB$FIELD_SOURCE)
WHERE r.RDB$PROCEDURE_NAME = 'QRESULT'
AND r.RDB$PARAMETER_TYPE = 1
ORDER BY r.RDB$PARAMETER_TYPE, r.RDB$PARAMETER_NUMBER
Note that the SP name should be in upper case as this is how it is stored into system tables (unless you use quoted identifiers). If you want to get both input and output parameters the delete the r.RDB$PARAMETER_TYPE = 1 predicate from the WHERE (type 0 is input parameters and 1 is output).
The type returned by this query is integer id for the type, quick googling found this:
14,"TEXT "
7,"SHORT "
8,"LONG "
9,"QUAD "
10,"FLOAT "
27,"DOUBLE "
35,"TIMESTAMP "
37,"VARYING "
261,"BLOB "
40,"CSTRING "
45,"BLOB_ID "
12,"DATE "
13,"TIME "
16,"INT64 "
but if you want to have more precise type then see this SO post.

concatenate without losing thousands separator

I have a report that brings total sales and total probability sale.
The request was that this be shown in one table as "R"{totalamount}" (R"{totprobamount")".
So i added this together in a variable with the variable expression being
"R" + $F{Totalt} +" (R" + $F{Totalp} +")"
but by doing this the Thousands separator does not show anymore?
If you can add a field for each value you wouldn't do this with String concatenation but by using patterns on text field. add for each field in the properties panel a patter such as R #,##0.00.
if it has to be in a single field you'd need to add an expression to actually format the numbers in the desired way such as for example: "R" + new DecimalFormat("#,##.00").format($F{Totalt}) + " (R" + new DecimalFormat("#,##.00").format($F{Totalp}) + ")"
You can use the FORMAT function to have thousand separator.
FORMAT({totalamount} +{totprobamount},2)
This column become String column so you have to add this column separately , you cant use same column for integer value. Where 2 is for up to 2 decimal value.