Postgresql - How to get largest value in column under constant - postgresql

How do I get the largest value in a column under a constant?
Specifically, in a table with a column of speed values how can I get the row with largest speed, under an arbitrary limit (say, 1200 mph)?
Thanks

Get a list of all the rows that fall below your maximum, then ORDER BY speed and LIMIT 1.
SELECT *
FROM your_table
WHERE speed < 1200
ORDER BY speed DESC
LIMIT 1;
If no row satisfies your criteria (i.e. the table is empty or every row has a speed larger than 1200), the query will return no rows. You should be prepared to handle this eventuality.

Unless I'm missing something, this is a simple max() with a where condition:
select max(speed)
from some_table
where speed < 1200;

Related

select only one record from a query which returns several rows

How do I retrieve only one row from a query which returns several?
Let's say I want only the 3 row?
This is the query but I want only the 3rd result
SELECT (journeys.id, j_starting_channel)
AS JER FROM JOURNEYS
WHERE j_starting_channel = 'channel_name' ORDER BY journeys.id;
The following should get you there:
SELECT (journeys.id, j_starting_channel)
AS JER FROM JOURNEYS
WHERE j_starting_channel = 'channel_name' ORDER BY journeys.id
LIMIT 1
OFFSET 2
LIMIT n will return the first n results. OFFSET m skips the first m rows and only returns everything thereafter.
LIMIT n OFFSET m thus returns rows m+1 to m+n.
See the PostgreSQL documentation for more details:
https://www.postgresql.org/docs/9.5/sql-select.html
If you just need to skip some rows then you can just use OFFSET to skip the rows in the top and then use LIMIT to return just one row
Like this:
SELECT (journeys.id, j_starting_channel)
AS JER FROM JOURNEYS
WHERE j_starting_channel = 'channel_name' ORDER BY journeys.id LIMIT 1 OFFSET 2
Here you have a step-by-step tutorial on those clauses
https://www.postgresqltutorial.com/postgresql-limit/
And you can always refer to the documentation too
by using OFFSET, LIMIT you can get needed portion of rows from result set
SELECT (journeys.id, j_starting_channel)
AS JER FROM JOURNEYS
WHERE j_starting_channel = 'channel_name' ORDER BY journeys.id OFFSET 2 LIMIT 1;

PostgreSQL - Comparing value based on condition (<, >, =) which written on a column?

I have this sample database:
Table 1:
Type Condition_weight Price
A >50 1000
A >10 & <50 500
A <10 100
As I remember, I can do a comparison on the Condition_weight without doing too much on query.
My expectation query is something like this:
select Price from Table_1
where Type = 'A'
and {my_input_this_is a number} satisfy Condition_weight
I read it somewhere about this solution but cant find it again.
You can create a function that returns true - you will have to do the logic to extract min and max and compare value.
pseudo code...
CREATE FUNCTION conditionWeightIsSatisfed(number weight)
BEGIN
set #minValue = 0;
set #MaxValue = 1000;
..... do your conversion of the text values.....
select weight >= #minValue and weight <= #maxValue
END

Calculating sum with no direct join column

I have a table (ShipJourneys) where I need to calculate the Total Fuel Consumed which is a float value. See the image below.
This value is obtained by summing all the individual consumers of fuel for a given vessel over the timeframe specified. This data is contained in a second table.
Boxed in area in red shows there were 5 fuel consumers (specified by the FK_RmaDataSumsystemConfigID) and that 3 of the consumers had burned 0 units of fuel and 2 had each burned 29.
To calculate the totalFuelConsumed for that range of time frames, for a given vessel (stipulated by the FK_RmaID), the following query could be used
Select sum(FuelCalc)
from FuelCalc
where Timestamp >= '2019-07-24 00:00:00'
and Timestamp <= '2019-07-24 00:02:00'
and FK_RmaID = 660
Using something like the query below does not work, resulting in bogus values
UPDATE ShipJourneys
SET TotalFuelConsumed =
(Select sum(FuelCalc) from FuelCalc as f
WHERE f.timestamp >= StartTimeUTC
and f.timestamp <= EndTimeUTC
and f.FK_RmaID = FK_RmaID)
Any suggestions on how I could join them
You could try something like that:
UPDATE myTable // Put the table correct name here
SET TotalFuelConsumed =
Select sum(FuelUsed) from FuelTimeTbl as fuelTbl
WHERE fuelTbl.timestamp >= '2019-10-21 22:13:55.000'
and fuelTbl.imestamp <= '2019-11-27 17:10:58.000'
and fuelTbl.FK_RmaID = myTable.RmaID // Put the correct attribute name

Postgresql upper limit of a calculated field

is there a way to set an upper limit to a calculation (calculated field) which is already in a CASE clause? I'm calculating percentages and, obviously, don't want the highest value exceed '100'.
If it wasn't in a CASE clause already, I'd create something like 'case when calculation > 100.0 then 100 else calculation end as needed_percent' but I can't do it now..
Thanks for any suggestions.
I think using least function will be the best option.
select least((case when ...), 100) from ...
There is a way to set an upper limit on a calculated field by creating an outer query. Check out my example below. The inner query will be the query that you have currently. Then just create an outer query on it and use a WHERE clause to limit it to <= 1.
SELECT
z.id,
z.name,
z.percent
FROM(
SELECT
id,
name,
CASE WHEN id = 2 THEN sales/SUM(sales) ELSE NULL END AS percent
FROM
users_table
) AS z
WHERE z.percent <= 1

How to get min/max of two integers in Postgres/SQL?

How do I find the maximum (or minimum) of two integers in Postgres/SQL? One of the integers is not a column value.
I will give an example scenario:
I would like to subtract an integer from a column (in all rows), but the result should not be less than zero. So, to begin with, I have:
UPDATE my_table
SET my_column = my_column - 10;
But this can make some of the values negative. What I would like (in pseudo code) is:
UPDATE my_table
SET my_column = MAXIMUM(my_column - 10, 0);
Have a look at GREATEST and LEAST.
UPDATE my_table
SET my_column = GREATEST(my_column - 10, 0);
You want the inline sql case:
set my_column = case when my_column - 10 > 0 then my_column - 10 else 0 end
max() is an aggregate function and gets the maximum of a row of a result set.
Edit: oops, didn't know about greatest and least in postgres. Use that instead.