Check if Integer is between a range of column values - sql

Consider the following table schema:
----------------------------------
| ID | MinValue | MaxValue |
----------------------------------
| 1 | 0 | 10 |
| 2 | 11 | 20 |
| 3 | 21 | 30 |
I want to be able to pass an integer, and have it return the appropriate ID where that value matches the range between Min and Max Value.
EG:
Input = 17
Output = 2
Input = 4
Output = 1
Input = 26
Output = 3
I thought I could do something like:
SELECT ID FROM MyTable WHERE MinValue >= #input AND MaxValue <= #input
But it doesn't work, nothing is returned.
I'm sure the solution is blatantly simple, but i'm stumped.
What's the best way to achieve this in SQL Server?

try this
SELECT ID FROM MyTable WHERE #input BETWEEN MinValue AND MaxValue
DESCRIPTION of BEETWEEN
The SQL BETWEEN Condition is used to retrieve values within a range in a SELECT, INSERT, UPDATE, or DELETE statement.
SYNTAX
The syntax for the SQL BETWEEN Condition is:
expression BETWEEN value1 AND value2;
Parameters or Arguments
expression is a column or calculation.
value1 and value2 create an inclusive range that expression is compared to.
NOTE
The SQL BETWEEN Condition will return the records where expression is within the range of value1 and value2 (inclusive).
ref: http://www.techonthenet.com/sql/between.php
or you can also use like
MinValue <= #input AND MaxValue >= #input

Try this,
SELECT ID FROM MyTable WHERE #input BETWEEN MinValue AND MaxValue.
Or flip the equality signs in your statement.
SELECT ID FROM MyTable WHERE MinValue <= #input AND MaxValue >= #input

Use BETWEEN
SELECT ID
FROM MyTable
WHERE #input BETWEEN MinValue AND MaxValue

Related

Replace values in a column for all rows

I have a column with entries like:
column:
156781
234762
780417
and would like to have the following:
column:
0000156781
0000234762
0000780417
For this I use the following query:
Select isnull(replicate('0', 10 - len(column)),'') + rtrim(column) as a from table)
However, I don't know how to replace the values in the whole column.
I already tried with:
UPDATE table
SET column= (
Select isnull(replicate('0', 10 - len(column)),'') + rtrim(column) as columnfrom table)
But I get the following error.
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
The answer to your question is going to depend on the data type of your column. If it is a text column for example VARCHAR then you can modify the value in the table. If it is a number type such as INT it is the value and not the characters which is stored.
We can also express this by saying that "0" + "1" = "01" whilst 0 + 1 = 1.
In either case we can format the value in a query.
create table numberz(
val1 int,
val2 varchar(10));
insert into numberz values
(156781,'156781'),
(234762,'234762'),
(780417,'780417');
/* required format
0000156781
0000234762
0000780417
*/
select * from numberz;
GO
val1 | val2
-----: | :-----
156781 | 156781
234762 | 234762
780417 | 780417
UPDATE numberz
SET val1 = isnull(
replicate('0',
10 - len(val1)),'')
+ rtrim(val1),
val2 = isnull(
replicate('0',
10 - len(val2)),'')
+ rtrim(val2);
GO
3 rows affected
select * from numberz;
GO
val1 | val2
-----: | :---------
156781 | 0000156781
234762 | 0000234762
780417 | 0000780417
select isnull(
replicate('0',
10 - len(val1)),'')
+ rtrim(val1)
from numberz
GO
| (No column name) |
| :--------------- |
| 0000156781 |
| 0000234762 |
| 0000780417 |
db<>fiddle here
Usually, when we need to show values in specificity format these processes are performed using the CASE command or with other functions on the selection field list, mean without updating. In such cases, we can change our format to any format and anytime with changing functions. As dynamic fields.
For example:
select id, lpad(id::text, 6, '0') as format_id from test.test_table1
order by id
Result:
id format_id
-------------
1 000001
2 000002
3 000003
4 000004
5 000005
Maybe you really need an UPDATE, so I wrote a sample query for an UPDATE command too.
update test.test_table1
set
id = lpad(id::text, 6, '0');

SQL updating a record in a table concerning another record in the same table

I have a table that contains more than 16,000,000 records.
Each record has a primary key (formed by five fields "tsid, plisid, plifc, plisc, dt"), and two counter fields ("icount, aicount").
There is a relation between some of the records in the table.
To simplify the problem let's say we have only these two records
tsid, plisid, plifc, plisc, dt, icount, aicount
10 1 0 0 0 2 2
11 1 0 0 0 7 0
The requirement:
I want to update the "aicount" field in the second record to be 9 (i.e. "icount" in the second record + "aicount" in the first record).
The relation between the first and second record is that they have the same values in (plisid, plifc, plisc, dt), and the tsid value of the second record == the tsid of the first record + 1
The desired result after the update is:
tsid, plisid, plifc, plisc, dt, icount, aicount
10 1 0 0 0 2 2
11 1 0 0 0 7 9
I tried this SQL statement in PostgreSQL but I got a syntax error "ERROR: syntax error at or near "SELECT" Position: 59"
UPDATE table1 SET
table1.aicount = table1.icount + SELECT COALESCE( (SELECT CASE
WHEN table1temp.aicount IS NULL
THEN 0
ELSE table1temp.aicount
END
FROM table1 table1temp
WHERE table1temp.tsid = table1.tsid - 1
AND table1temp.plisid = table1.plisid
AND table1temp.plifc = table1.plifc
AND table1temp.plisc = table1.plisc
AND table1temp.dt = table1.dt), 0)
WHERE table1.tsid = 10;
What is the wrong in the statement above? Any idea or suggestions?
The error caused because you couldn't use select subquery to add an update column.
You seem to want to get the number, which this row icount number add with last recorded aicount number
I would use LAG function to get last recorded aicount number in subquery then update the number.
There are three parameters in LAG function.
First your column, which you want to get the last column value.
offset from this column value defaults to 1
default value. default to null
lag(value any [, offset integer [, default any ]])
returns value evaluated at the row that is offset rows after the current row within the partition; if there is no such row, instead return default. Both offset and default are evaluated with respect to the current row. If omitted, offset defaults to 1 and default to null
CREATE TABLE T(
tsid int,
plisid int,
plifc int,
plisc int,
dt int,
icount int,
aicount int
);
INSERT INTO T VALUES (10,1,0,0,0,2,2);
INSERT INTO T VALUES (11,1,0,0,0,7,0);
UPDATE T
SET aicount = t1.totle
FROM
(
SELECT *,(LAG(aicount,1,0) over(order by tsid) + icount) totle
FROM T
) t1
WHERE
T.tsid = t1.tsid
AND T.plisid = t1.plisid
AND T.plifc = t1.plifc
AND T.plisc = t1.plisc
AND T.dt = t1.dt
Query 1:
SELECT * FROM T
Results:
| tsid | plisid | plifc | plisc | dt | icount | aicount |
|------|--------|-------|-------|----|--------|---------|
| 10 | 1 | 0 | 0 | 0 | 2 | 2 |
| 11 | 1 | 0 | 0 | 0 | 7 | 9 |
Try the following query-:
update T
set aicount=mm.m
from(
select sum(iCount) over (partition by plisid,plifc,plisc,dt order by tsid) m from T
) mm
SQL Server

Where to find Netezza Sequence data?

Information about sequences can be found in the _vt_sequence view which can be joined with _v_sequence on _v_sequence.objid = _vt_sequence.seq_id.
sequence fetch query :
select vs.* , vts.*
from _v_sequence vs join _vt_sequence vts on vs.objid = vts.seq_id;
Following values generated out of queries :
OBJID
SEQNAME
OWNER
CREATEDATE
OBJTYPE
OBJCLASS
OBJDELIM
DATABASE
OBJDB
SCHEMA
SCHEMAID
SEQ_ID
DB_ID
DATA_TYPE
MIN_VALUE
MAX_VALUE
CYCLE
INCREMENT
CACHE_SIZE
NEXT_CACHE_VAL
FLAGS
Sample CREATE SEQUNCE:
CREATE SEQUENCE TEMP_PPC_SEQ AS BIGINT
START WITH 1
INCREMENT BY 2
NO MINVALUE
MAXVALUE 2147483647
NO CYCLE;
There is no value for START of sequence.
Help to fetch START value of each sequence.
You can find start value in sequence table. Unfortunately netezza don't update last value in this table. Your answer is
SELECT s.LAST_VALUE
FROM sequence1 s;
You can find the "START WITH" value used by the DDL at creation time by selecting from the sequence object itself, as if it were a table, and referencing the LAST_VALUE column.
Don't be confused by the column name. LAST_VALUE does not report the last value dispensed by the sequence. The below example demonstrates this.
TESTDB.ADMIN(ADMIN)=> create sequence test_seq_1 as bigint start with 12345;
CREATE SEQUENCE
TESTDB.ADMIN(ADMIN)=> create temp table seq_out as select next value for test_seq_1 from _v_vector_idx a cross join _v_vector_idx b;
INSERT 0 1048576
TESTDB.ADMIN(ADMIN)=> select * from test_seq_1;
SEQUENCE_NAME | LAST_VALUE | INCREMENT_BY | MAX_VALUE | MIN_VALUE | CACHE_VALUE | LOG_CNT | IS_CYCLED | IS_CALLED | DATATYPE
---------------+------------+--------------+---------------------+-----------+-------------+---------+-----------+-----------+----------
TEST_SEQ_1 | 12345 | 1 | 9223372036854775807 | 1 | 100000 | 1 | f | f | 20
(1 row)
TESTDB.ADMIN(ADMIN)=> select next value for test_seq_1;
NEXTVAL
---------
1060921
(1 row)

Use WITH to loop over a set of data in SQL

Given the following fields below, I'm trying to loop to the first iteration of the total set of iterations.
+-------------------+----------------------+------------------------+
| id | nextiterationId | iterationCount |
+-------------------+----------------------+------------------------+
| 110001 | 110002 | 0 |
| 110002 | 110003 | 1 |
| 110003 | 110004 | 2 |
| 110004 | 1 | 3 |
So if I call a SP/function using one of the values of the id field, I need it return the prior iterations of the id given until iterationCount = 0.
So If I use id of 110003(send that as the parameter), the first thing it should query is an id field having a nextIterationID of 110003. That would be the first loop.
Since the iterationCount is not 0 yet, it would keep looping. Then it would look for an id where nextIterationID is 110002 based on first loop determination, so second loop will find "id" of 110001 and return it. And since that record iterationCount = 0, it would stop the loop.
It's okay if I call the SP/function using 110003, which is the 3rd iteration, and it would not return the 110004, 4th iteration. I only need it to go back given the id.
A while ago I did this using a WITH and maybe WHILE using both somehow, but I can't recall how to do this now. I need the format returned in a way so that I can use it in a larger SELECT statements.
Here is a recursive cte solution. Let me know if it needs any tweaks.
--Throwing your table into a temp table
CREATE TABLE #yourTable (ID INT,NextIterationID INT,IterationCount INT)
INSERT INTO #yourTable
VALUES
(110001,110002,0),
(110002,110003,1),
(110003,110004,2),
(110004,1,3)
--Now for the actual work
--Here is your parameter
DECLARE #param INT = 110003;
--Recursive CTE
WITH yourCTE
AS
(
--Initial Row
SELECT ID,
NextIterationID,
IterationCount
FROM #yourTable
WHERE NextIterationID = #param
UNION ALL
--Finding all previous iterations
SELECT #yourTable.*
FROM #yourTable
INNER JOIN yourCTE
ON yourcte.ID = #yourTable.NextIterationID
--Where clause is not really necessary because once there are no more previous iterations, it will automatically stop
--WHERE yourCTE.IterationCount >= 0
)
SELECT *
FROM yourCTE
--Cleanup
DROP TABLE #yourTable
Results:
ID NextIterationID IterationCount
----------- --------------- --------------
110002 110003 1
110001 110002 0

SQL SELECT what in range number

I need help to solve my issue.
I have a table like this one,
id | Desc | Min Range | Max Range
-----------------------------------
1 | A | 0 | 10
2 | B | 11 | 20
3 | C | 21 | 30
How to get the second record when I put parameter 20.
My solution now is like this:
select * from table where maxRange <= 20
and in java, I get last of result list.
My problem is I don't have parameter to compare when I use between. eg.
select * from table where maxRange between ? and ?
select * from table where ? between minrange and maxrange
You need to add the parameter to you command when you query.
Create a Parameter called #Parameter with value 20 - this is dependant on what technology you are using. Then:
SELECT * FROM table WHERE #Parameter >= MinRange AND #Parmeter <=
MaxRange