How select the min between a SQL value and a fixed number - sql

I have to run this query in SQL that will return the min between a fixed scalar (let's say 7) and the value in the column. I tried:
SELECT from theTable min(theTable.Column , 7) AS Label
I get an error saying that I am using the wrong number of arguments in a function on this expression. I cannot copy/paste because I am using Access.

Try this
SELECT
IIF(theTable.Column < 7, theTable.Column, 7) AS Label
FROM
theTable

Related

SQL Server using IIF resulted AS column in another IIF [duplicate]

This question already has answers here:
Possible to store value of one select column and use it for the next one?
(4 answers)
Using alias in query and using it
(6 answers)
Why can't I use column aliases in the next SELECT expression?
(4 answers)
Closed 9 months ago.
on SQL Server 2012+ I am attempting to use IIF resulted column into another IIF as shown in SQL query below but it is gives me error invalid column. Count table has columns CountId and CountedQty,
SELECT CountId, IIF(CountId<5, 3,2) as MyGroup, IIF([MyGroup]<5, 3,2) as GName FROM Count
Error shown for this query execution is Invalid column name 'MyGroup' if there any way to use IIF resulted column into another IIF in same query
similarly for following query it shows invalid column names errors
SELECT
Count.StockCountId,
Count.CountedQty,
IIf(Count.CountedQty > 0, 1, IIf(Count.CountedQty = 0, 3, 2)) AS MyGroup,
IIf([MyGroup] = 1, "Additional products counted", IIf([MyGroup] =2, "Insufficient products counted", "Matched Count")) AS GName
FROM Count
it returns following errors
Invalid column name 'MyGroup'.
Invalid column name 'Additional products counted'.
Invalid column name 'MyGroup'.
Invalid column name 'Insufficient products counted'.
Invalid column name 'Matched Count'.
what changes are needed to use IIF resulted columns into above query to resolve errors and get intended output
You cannot reference a column alias like that, at the time query execution reaches select it does not yet exist.
You can use a derived table or CTE and then reference the column in an outer query, you can repeat the expression, or in SQL Server you could use apply.
Your logic seems a little odd however as you'll always return 3 since MyGroup is always < 5 in this example.
select CountId, Iif(MyGroup < 5, 3, 2) as GName
from [Count]
cross apply(values(Iif(CountId < 5, 3, 2)))c(MyGroup);

OracleSQL get substring of variable as new variable

I have a column and I would like to get a new column using only the first two characters. I would have assumed the following should work, but it throws FROM keyword not found where expected error
SELECT *,
SUBSTR(PHONE_NUMBER , 1,2) AS MY_PHONE_NUMBER
FROM PHONE_NOS;
Try it here
Alias the table and use it in the statement:
SELECT p.*,
SUBSTR(p.PHONE_NUMBER, 1, 2) AS MY_PHONE_NUMBER
FROM PHONE_NOS p;

Selecting values from a query that are negative in Sybase

Im running the query
SELECT ART_REF FROM tablename WHERE SEMESTER_NUM=28
This query returns both positive negative a 0 results in the forms of 8, -2, 0.
how can i just return the values that are negative (-8)?
I've tired using the LIKE operator but with no success.
Cheers
Try this way:
SELECT ART_REF
FROM tablename
WHERE SEMESTER_NUM=28
AND ART_REF <0

How to limit the maximum display length of a column in PostgreSQL

I am using PostgreSQL, and I have a column in a table which contains very long text. I want to select this column in a query, but limit its display length.
Something like:
select longcolumn (only 10 chars) from mytable;
How would I do this?
What you can do is use PostgreSQL's substring() method. Either one of the two commands below will work:
SELECT substring(longcolumn for 10) FROM mytable;
SELECT substring(longcolumn from 1 for 10) FROM mytable;
Slightly shorter:
SELECT left(longcolumn, 10) from mytable;

Problems with Postgresql CASE syntax

Here is my SQL query:
SELECT (CASE (elapsed_time_from_first_login IS NULL)
WHEN true THEN 0
ELSE elapsed_time_from_first_login END)
FROM (
SELECT (now()::ABSTIME::INT4 - min(AcctStartTime)::ABSTIME::INT4)
FROM radacct
WHERE UserName = 'test156') AS elapsed_time_from_first_login;
When I execute the above query, I get this error:
ERROR: CASE types record and integer cannot be matched
From the error message I understand that PostgreSQL take the second select, respectively elapsed_time_from_first_login as a row, even if it will always be a single value (because of the min() function).
Question: do you have some suggestions on how to deal with this query?
I suppose, what you are actually trying to do should look like this:
SELECT COALESCE((SELECT now() - min(acct_start_time)
FROM radacct
WHERE user_name = 'test156')
, interval '0s')
While there is an aggregate function in the top SELECT list of the subselect, it cannot return "no row". The aggregate function min() converts "no row" to NULL, and the simple form below also does the trick.
db<>fiddle here
Oldsqlfiddle
Other problems with your query have already been pointed out. But this is the much simpler solution. It returns an interval rather than an integer.
Convert to integer
Simplified with input from artaxerxe.
Simple form does the job without check for "no row":
SELECT COALESCE(EXTRACT(epoch FROM now() - min(acct_start_time))::int, 0)
FROM radacct
WHERE user_name = 'test156';
Details about EXTRACT(epoch FROM INTERVAL) in the manual.
Aggregate functions and NULL
If you had used the aggregate function count() instead of sum() as you had initially, the outcome would be different. count() is a special case among standard aggregate functions in that it never returns NULL. If no value (or row) is found, it returns 0 instead.
The manual on aggregate functions:
It should be noted that except for count, these functions return a
null value when no rows are selected. In particular, sum of no rows
returns null, not zero as one might expect, and array_agg returns
null rather than an empty array when there are no input rows. The
coalesce function can be used to substitute zero or an empty array for
null when necessary.
Postgres is complaining that 0 and elapsed_time_from_first_login are not the same type.
Try this (also simplifying your select):
select
coalesce(elapsed_time_from_first_login::INT4, 0)
from ...
Here is how I formatted the SQL and now is working:
SELECT coalesce(result, 0)
FROM (SELECT (now()::ABSTIME::INT4 - min(AcctStartTime)::ABSTIME::INT4) as result
FROM radacct WHERE UserName = 'test156') as elapsed_time_from_first_login;
The second SELECT is returning a table, named elapsed_time_from_first_login with one column and one row. You have to alias that column and use it in the CASE clause. You can't put a whole table (even if it is one column, one row only) where a value is expected.
SELECT (CASE (elapsed_time IS NULL)
WHEN true THEN 0
ELSE elapsed_time end)
FROM (SELECT (now()::ABSTIME::INT4 - min(AcctStartTime)::ABSTIME::INT4)
AS elapsed_time -- column alias
FROM radacct
WHERE UserName = 'test156'
) as elapsed_time_from_first_login; -- table alias
and you can shorten the CASE by using the COALESCE() function (and optionally add an alias for that column to be shown in the results):
SELECT COALESCE(elapsed_time, 0)
AS elapsed_time
FROM (SELECT (now()::ABSTIME::INT4 - min(AcctStartTime)::ABSTIME::INT4)
AS elapsed_time
FROM radacct
WHERE UserName = 'test156'
) as elapsed_time_from_first_login; -- table alias