Rails: Postgres JSONB "between" query [duplicate] - ruby-on-rails

This question already has an answer here:
PostgreSQL jsonb value in WHERE BETWEEN clause
(1 answer)
Closed 3 years ago.
I'm working with Rails 5 + Postgres.
I have a Postgres JSONB column named data with data that looks something like:
{username: 'McGruff', timestamp: 123456789}
I would like to query for data that is between two timestamps, to get a subset of records that all have a timestamp within some range (say, the last 24 hours).
Using comments from below, the answer is:
Model.where("(data->'timestamp')::int BETWEEN ? AND ?", start, end)
Thanks for the help!

Use where clause by providing start & end inputs as strings. as the data stored in string format in jsonb column.
somewhat like below:
Model.where((data->>'timestamp')::int between ? and ?, start, end)

Related

How can I add the results from 3 query statements? [duplicate]

This question already has answers here:
IF + AND / OR logic inside of a query
(1 answer)
How to calculate a sum conditionally based on the values of two other columns
(2 answers)
Closed 4 months ago.
To get the number of flight cancellations in any given month, I'm using a COUNTIFS statement, as follows:
=COUNTIFS(QF_Data_2022!C$2:C,"September",QF_Data_2022!E$2:E,"canceled",QF_Data_2022!F$2:F,"MIA")
Where Col_C is the month, Col_E is the flight status, and Col_F is the airport code.
It works great.
But in an effort to obtain figures that reflect more than a single month (i.e. Q3), the approach of adding the following conditions on the same column (C) is not working:
(...QF_Data_2022!C$2:C,"September",QF_Data_2022!C$2:C,"August",QF_Data_2022!C$2:C,"July"...)
So I've moved to a QUERY function:
=QUERY(QF_Data_2022!A2:R, "SELECT COUNT(C) WHERE C='July' OR C='August' OR C='September' AND E='CANCELED' AND F='MIA' LABEL COUNT(C) '' ")
BUT the result gives me an integer that is FAR too high (e.g. 3770 results out of 5800 rows, when the actual number should be about 164).
So, is something like the following possible:
SUM = QUERY 1 + QUERY 2 + QUERY 3
Or is there a better approach altogether?

How to workaround Query with a mixed-data column? (google sheets) [duplicate]

This question already has answers here:
Query is ignoring string (non numeric) value
(2 answers)
Closed 5 months ago.
I have a simple Query that groups my data by months that was working fine before, but now that I've introduced a formula into my date column, it's not working anymore. (I'm guessing it's because the majority data in the column is now formulas instead of actual dates).
=Query(C5:L,"SELECT SUM(I) pivot MONTH(C)+1",1)
Is there a way for me to still get my intended Query data without removing my formulas in the date column? (Query formula is in M2)
Thank you in advance!
Link to sheet: https://docs.google.com/spreadsheets/d/1EpvLMboKJ0KeR7tTqBarF1AnAg3jelhKTkyBhwKNlK4/edit#gid=1335125620
Your formulas in Col C seem to be causing the issue since they're adding a blank space when there is no corresponding value in Col D:
=IF(D45=""," ",TIMESTAMP())
Instead, try:
=IF(D45="",,TIMESTAMP())

Some data removed after query [duplicate]

This question already has answers here:
Query is ignoring string (non numeric) value
(2 answers)
Closed 5 months ago.
I have a google sheet https://docs.google.com/spreadsheets/d/1mUV9DpVJHC2UbyqOG49wUIRj3EflTlB9etJQFssRLvo/ with a column "Floor", it contains the number and also character, I want to query the column and remove all empty cell, =unique(query(A:A,"SELECT A WHERE A IS NOT NULL ORDER BY A")) only the number be queried and all characters have been removed.
Can anyone advise how I can query all with unique and sort function?
I read the article from https://webapps.stackexchange.com/questions/101778/google-sheets-query-wont-display-cell-text-if-other-cells-have-numbers and come up a solution, hope this can help others.
=UNIQUE(ARRAYFORMULA(QUERY(TO_TEXT(A2:A), "SELECT Col1 WHERE Col1 IS NOT NULL ORDER BY Col1")))
Reason of using TO_TEXT() because mixed data types in a single column in Google Sheet, the majority data type determines the data type of the column for query purposes, so I convert all into text format.
Ref: https://support.google.com/docs/answer/3094285?hl=en
UNIQUE is used to filter out all duplicated values
Regarding ARRAYFORMULA() function, I don't know why it is needed but QUERY() will return #VALUE! if missing the ARRAYFORMULA().
If someone can explain the use of ARRAYFORMULA() and Col1 reference, appreciate to answer.
use the filter function instead.
considering Column A has both numbers and characters.
in B2, write: =filter(A2:A,isnumber(A2:A))
let me know if you need help!

How to convert postgres column type from string to float

I have a rails app with a basic postgres db, but I realized that some of my columns are strings and it'd be best if they were floats. I'm trying to convert columns for latitude and longitude from varchar to floating-point.
I've tried this post Rails - gmaps4rails gem on postgres but I kept getting this error, ERROR: invalid input syntax for type double precision: "". I'm willing to try anything else, and I've seen solutions for ways to do it with postgres queries, but I'm uncertain of how to implement them. It's a straightforward problem; "-73.88537758790638" I want to become -73.88537758790638. I just can't seem to find a working solution or one that I understand how to implement.
Empty strings cannot be converted to a number for obvious reasons.
You have to account for that. Replace all occurrences with NULL or 0 or something compatible.
For the number of fractional digits in your example you want the data type numeric, not float - neither real (float4) nor double precision (float8). Those are lossy types and not exact enough. See:
Fetch records that are non zero after the decimal point in PostgreSQL
Try for yourself:
SELECT '-73.88537758790638'::real AS _float4
,'-73.88537758790638'::double precision AS _float8
,'-73.88537758790638'::numeric AS _numeric;
Result (up to Postgres 11):
_float4 | _float8 | _numeric
---------+-------------------+-------------------
-73.8854 | -73.8853775879064 | -73.88537758790638
db<>fiddle here
Display improved in Postgres 12 (more extra_float_digits by default):
db<>fiddle here
Numeric types in the manual.
Solution
Single SQL statement (replacing empty strings with NULL):
ALTER TABLE tbl
ALTER COLUMN col1 TYPE numeric USING NULLIF(col1, '')::numeric;
This is a really simple thing to do in rails using a native ORM approach:
change_column :restaurants, :column_name, ‘double precision USING CAST(column_name AS double precision)'

Rails how to find record where the value is least? [duplicate]

This question already has answers here:
Rails ActiveRecord conditions
(4 answers)
Closed 2 years ago.
I have a table named Socks and it have a column named water (integer).
I want to find all records where the column water is at least 40
Example if the water column is 400 the record would be found, but not if the value was 39.
Think the easiest thing to do would be to use the where method:
Sock.where("water >= ?", 40)
Sock.where("water >= ?", 40).first
Sock.where("water >= ?", 40).last
to work on a specific model and not getting an array of models.

Resources