Max() in LINQ Query - asp.net-mvc

I have a Column with DataType as Nvarchar(max)
Sample Records:
Advisor_Code
9001
9002
9003
100001
100001
9011
I have tried this Query :
var code = (from a in db.advisor_Registration select a ).Max(a=>a.advisor_Code);
It Returns 9011 but max Number is 100001 .
How to fix it

Since one of the tags is entity-framework I assume it should be translatable into SQL. If you use e.g. Convert.ToInt32 in the LINQ statement, this won't succeed.
A common way to get the "numeric" max out of strings without conversion is to order by length and then by string:
var max = myquery.OrderByDescending(x => x.Length)
.ThenByDescending (x => x)
.First();
where myquery could be any query against a DbSet that returns strings. Of course the results will be meaningless if any of the strings is not numeric.

You can only perform a MAX function with your expected result on a numeric field. nvarchar(max) is not a numeric field. You would have to convert the strings to a long, for example, then take the MAX for MAX to work as you are expecting.

Related

convert neo4j cypher list of integer not working

I have list property [1,2,2,0]. The value is the list default to type of long. To convert to a list of type integer I am using
apoc.convert.toIntList([1,2,2,0])
but the result is still a list of type long.....however
apoc.convert.toStringList([1,2,2,0])
does result in a list of strings. This my query:
MERGE (bs:Bslot {date: $date})
ON CREATE
SET bs.slots = [1,2,2,0]
RETURN {slots: apoc.convert.toIntList(bs.slots)}
What am I doing wrong here?
It is working as expected; see below example:
WITH [1,2,2,0.99] as slots
RETURN {slots: apoc.convert.toIntList(slots)}
Result:
╒════════════════════════════════════════╕
│"{slots: apoc.convert.toIntList(slots)}"│
╞════════════════════════════════════════╡
│{"slots":[1,2,2,0]} │
└────────────────────────────────────────┘
Notice that 0.99 (float) becomes an integer.
In your example; MERGE will not update slots property when that node Bslot with date equals $date. It is because it will only set the value of slots to [1,2,2,0] if that node is new (create).

Is there an way through we can fetch data from neo4j database based on different conditions

MATCH (a:Chemical{name:'abc'})-[r:On_Reacting_With]->(b:Chemical)
WHERE r.outputtime >'20'
RETURN count(b)
As in the above query I can get values where the outputtime is greater than 20. But I want to give the user a feature where he/she can fetch the data where outoutime can be greater, lesser or equal to a value. I want to know how can we pass the operator as params in code.
Aside: using string values for time comparison will not produce correct results unless all strings have the same length (including leading zero characters, as needed).
You can pass in an operator parameter and use a CASE clause. For instance:
MATCH (a:Chemical{name:'abc'})-[r:On_Reacting_With]->(b:Chemical)
WHERE
CASE $operator
WHEN '<' THEN r.outputtime < '20'
WHEN '>' THEN r.outputtime > '20'
ELSE r.outputtime = '20'
END
RETURN COUNT(b)

Query jsonb array for integer member

Background: We use PaperTrail to keep the history of our changing models. Now I want to query for a Item, which belonged to a certain customer. PaperTrail optionally stores the object_changes and I need to query this field to understand, when something was created with this ID or changed to this ID.
My table looks simplified like this:
item_type | object_changes
----------|----------------------------------------------------------
"Item" | {"customer_id": [null, 5], "other": [null, "change"]}
"Item" | {"customer_id": [4, 5], "other": ["unrelated", "change"]}
"Item" | {"customer_id": [5, 6], "other": ["asht", "asht"]}
How do I query for elements changed from or to ID 5 (so all rows above)? I tried:
SELECT * FROM versions WHERE object_changes->'customer_id' ? 5;
Which got me:
ERROR: operator does not exist: jsonb ? integer
LINE 1: ...T * FROM versions WHERE object_changes->'customer_id' ? 5;
^
HINT: No operator matches the given name and argument type(s).
You might need to add explicit type casts.
For jsonb the contains operator #> does what you ask for:
Get all rows where the number 5 is an element of the "customer_id" array:
SELECT *
FROM versions
WHERE object_changes->'customer_id' #> '5';
The #> operator expects jsonb as right operand - or a string literal that is valid for jsonb (while ? expects text). The numeric literal without single quotes you provided in your example (5) cannot be coerced to jsonb (nor text), it defaults to integer. Hence the error message. Related:
No function matches the given name and argument types
PostgreSQL ERROR: function to_tsvector(character varying, unknown) does not exist
This can be supported with different index styles. For my query suggested above, use an expression index (specialized, small and fast):
CREATE INDEX versions_object_changes_customer_id_gin_idx ON versions
USING gin ((object_changes->'customer_id'));
This alternative query works, too:
SELECT * FROM versions WHERE object_changes #> '{"customer_id": [5]}';
And can be supported with a general index (more versatile, bigger, slower):
CREATE INDEX versions_object_changes_gin_idx ON versions
USING gin (object_changes jsonb_path_ops);
Related:
Index for finding an element in a JSON array
Query for array elements inside JSON type
According to the manual, the operator ? searches for any top-level key within the JSON value. Testing indicates that strings in arrays are considered "top-level keys", but numbers are not (keys have to be strings after all). So while this query would work:
SELECT * FROM versions WHERE object_changes->'other' ? 'asht';
Your query looking for a number in an array will not (even when you quote the input string literal properly). It would only find the (quoted!) string "5", classified as key, but not the (unquoted) number 5, classified as value.
Aside: Standard JSON only knows 4 primitives: string, number, boolean and null. There is no integer primitive (even if I have heard of software adding that), integer is a just a subset of number, which is implemented as numeric in Postgres:
https://www.postgresql.org/docs/current/static/datatype-json.html#JSON-TYPE-MAPPING-TABLE
So your question title is slightly misleading as there are no "integer" members, strictly speaking.
Use a lateral join and the jsonb_array_elements_text function to process each row's object_changes:
SELECT DISTINCT v.* FROM versions v
JOIN LATERAL jsonb_array_elements_text(v.object_changes->'customer_id') ids ON TRUE
WHERE ids.value::int = 5;
The DISTINCT is only necessary if the customer_id you're looking for could appear multiple times in the array (if a different field changed but customer_id is tracked anyway).

Can't get children multiply values using XMLTABLE

guys, i'm trying to get values from the next query
SELECT X.val, X.tdate
FROM
XMLTABLE ('$d/IRR' passing XMLPARSE(DOCUMENT '<IRR><value>2</value><tdate>2014-06-05</tdate><value>4</value><tdate>2014-08-05</tdate></IRR>') as "d"
COLUMNS
val DOUBLE PATH './value',
tdate DATE PATH './tdate' ) AS X;
but I always get the error:
An expression of data type "( item(), item()+ )" cannot be used when
the data type "DATE" is expected in the context
at the same time everything works fine if there is only one value and date like
SELECT X.val, X.tdate
FROM
XMLTABLE ('$d/IRR' passing XMLPARSE(DOCUMENT '<IRR><value>2</value><tdate>2014-06-05</tdate></IRR>') as "d"
COLUMNS
val DOUBLE PATH './value',
tdate DATE PATH './tdate' ) AS X;
And as I understand here it's because XMLTABLE waits only for 1 value and it cann't parse the doc if there are few of them
What's more it works fine if there is only 1 column need to be returned like this even though there are a few values:
SELECT X.tdate
FROM
XMLTABLE ('$d/IRR/tdate' passing XMLPARSE(DOCUMENT '<IRR><value>2</value><tdate>2014-06-05</tdate><value>4</value><tdate>2014-08-05</tdate></IRR>') as "d"
COLUMNS
tdate DATE PATH '.' ) AS X;
So this query returns both dates.
tdate
2014-06-05
2014-08-05
So is there any way to return both columns with multiply values in the same query?
e.g.
val tdate
2 2014-06-05
4 2014-08-05
Note: that is the representation of the xml document which is passed in my procedure (it could contain more than 2 values)
<IRR><value>2</value><tdate>2014-06-05</tdate><value>4</value><tdate>2014-08-05</tdate></IRR>
XMLTABLE() can return a special ordinality column, containing the sequential number of each row. You can use it to do something like:
WITH t(x) AS (VALUES XMLPARSE(DOCUMENT '<IRR><value>2</value><tdate>2014-06-05</tdate><value>4</value><tdate>2014-08-05</tdate></IRR>'))
SELECT x1.value, x2.tdate
FROM
t,
XMLTABLE ('$X//value'
COLUMNS
value INT PATH '.',
idx FOR ORDINALITY) AS X1,
XMLTABLE ('$X//tdate'
COLUMNS
tdate DATE PATH '.',
idx FOR ORDINALITY) AS X2
WHERE x1.idx = x2.idx
ORDER BY 2
This assumes that the XML parser preserves the element order, which, although not explicitly documented, seems to be the case with all parsers I've worked with.
Ideally you should rethink your XML schema, for example, passing tdate as an attribute of value (or vice versa).

Ruby on Rails query returns extra column

I am working with Ruby 2.0.0 and Rails 4.0.9, on Oracle 11g database.
I query the database to get pairs of values [date, score] to draw a chart.
Unfortunately, my query returns triplets such as [date, score, something], and the chart fails.
Here is the query:
#business_process_history = DmMeasure.where("period_id between ? and ? and ODQ_object_id = ?",
first_period_id, current_period_id, "BP-#{#business_process.id}").
select("period_day, score").order("period_id")
Here is the result in the console:
DmMeasure Load (1.2ms) SELECT period_day, score FROM "DM_MEASURES" WHERE (period_id between 1684 and 1694 and ODQ_object_id = 'BP-147') ORDER BY period_id
=> #<ActiveRecord::Relation [#<DmMeasure period_day: "20140811", score: #<BigDecimal:54fabf0,'0.997E2',18(45)>>,
#<DmMeasure period_day: "20140812", score: #<BigDecimal:54fa7e0,'0.997E2',18(45)>>, ...]
Trying to format the result also returns triplets:
#business_process_history.map { |bp| [bp.period_day, bp.score] }
=> [["20140811", #<BigDecimal:54fabf0,'0.997E2',18(45)>],
["20140812", #<BigDecimal:54fa7e0,'0.997E2',18(45)>], ...]
Where does this come from?
How can I avoid this behaviour?
Thanks for your help,
Best regards,
Fred
what triplets? From what I can see, you have two attributes per item: 'period_day' (a string representing a date) and 'score' (a BigDecimal representation of a single number).
The ruby BigDecimal is just one way of representing a number.
eg if you play around with them in the rails console:
> BigDecimal.new(1234)
=> #<BigDecimal:f40c6d0,'0.1234E4',9(36)>
The first part, as you can see, a bit like scientific notation, it contains the significant digits and precision.
To figure out what the 18(45) is, I had to dig into the original c-code for the BigDecimal#inspect method.
Here's the commenting for that method:
/* Returns debugging information about the value as a string of comma-separated
* values in angle brackets with a leading #:
*
* BigDecimal.new("1234.5678").inspect ->
* "#<BigDecimal:b7ea1130,'0.12345678E4',8(12)>"
*
* The first part is the address, the second is the value as a string, and
* the final part ss(mm) is the current number of significant digits and the
* maximum number of significant digits, respectively.
*/
The answer being: the current number of significant digits and the maximum number of significant digits, respectively

Resources