Adding values from previous row into current row - sql

I have a simple table and I want add a value from previous row into current and value of current in next row so it keeps on going until the end.
Please have a look at the following table data.
ID Value ValueIncrement
1 2 0
2 3 5 (2+3)
3 9 14 (2+3+9)
4 6 20 (2+3+9+6)
5 3 23 (2+3+9+6+3)
6 1 24 (2+3+9+6+3+1)
7 2 26 (2+3+9+6+3+1+2)
8 0 26 (2+3+9+6+3+1+2+0)
9 2 30 (2+3+9+6+3+1+2+0+2)
I am looking for a select query which can enable me to add values continuously.

You can do a window sum:
select id, value, sum(value) over (order by id) valueincrement
from mytable
order by id
Demo on SQL Server 2014 Fiddle:
id | value | valueincrement
-: | ----: | -------------:
1 | 2 | 2
2 | 3 | 5
3 | 9 | 14
4 | 6 | 20
5 | 3 | 23
6 | 1 | 24
7 | 2 | 26
8 | 0 | 26
9 | 2 | 28

You could also use a correlated sub-query if you are working with a small table (otherwise,for performance reason, you should absolutely not use this approach if you can use window-functions). I am assuming your valueincrement column starting with a 0 is a typo and not by design. Let us know if otherwise.
select *, (select sum(value) from mytable t2 where t1.id >= t2.id) as valueincrement
from mytable t1
order by id;

You can try a recursive sum
INSERT INTO #tmpPrueba
VALUES(2),(3),(9),(6),(3),(1),(2),(0),(2)
CREATE TABLE #tmpTest
(nId INT IDENTITY(1,1),
nValor INT NOT NULL)
SELECT *
FROM #tmpTest;
SELECT SUM(nValor) OVER (ORDER BY nId ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
FROM #tmpTest;

Related

Selecting the first row of group with additional group by columns

Say I have a table with the following results:
How is it possible for me to select such that I only want distinct parent_ids with the min result of object0_behaviour?
Expected output:
parent_id | id | object0_behaviour | type
------------------------------------------
1 | 1 | 5 | IP
2 | 3 | 5 | IP
3 | 5 | 7 | ID
4 | 6 | 7 | ID
5 | 8 | 5 | IP
6 | 18 | 7 | ID
7 | 10 | 7 | ID
8 | 9 | 5 | IP
I have tried:
SELECT parent_id, min(object0_behaviour) FROM table GROUP BY parent_id
It works, however if I wanted the other 2 additional columns, I am required to add into GROUP BY clause and things go back to square one.
I saw examples with R : Select the first row by group
Similar output from what I need, but I can't seem to convert it into SQL
You can try using row_number() window function
select * from
(
select *, row_number() over(partition by parent_id order by object0_behaviour) as rn
from tablename
)A where rn=1
select * from table
join (
SELECT parent_id, min(object0_behaviour) object0_behaviour
FROM table GROUP BY parent_id
) grouped
on grouped.parent_id = table.parent_id
and grouped.object0_behaviour = table.object0_behaviour

Setting batch number for set of records in sql

I have following table in SQL
id,date,records
1,2019-03-28 01:22:12,5
2,2019-03-29 01:23:23,5
3,2019-03-30 01:28:54,5
4,2019-03-28 01:12:21,2
5,2019-03-12 01:08:11,1
6,2019-03-28 01:01:21,12
7,2019-03-12 01:02:11,1
What i am trying to achieve is set a batch number that should keep on increasing after moving sum value crosses 15 and the moving sum should reset as well, so i am trying to create batch for records that has total moving sum value as 15
For ex. if Moving sum becomes 15 the batch number value should increment, which would given me rows containing total value of 15.
so the output i am looking for is
id,date,records, moving_sum,batch_number
1,2019-03-28 01:22:12,5,5,1
2,2019-03-29 01:23:23,5,10,1
3,2019-03-30 01:28:54,5,15,1
4,2019-03-28 01:12:21,2,2,2
5,2019-03-12 01:08:11,1,1,2
6,2019-03-28 01:01:21,2,12,2
7,2019-03-12 01:02:11,1,1,3
You need a recursive query for this:
with
tab as (select t.*, row_number() over(order by id) rn from mytable t),
cte as (
select
id,
date,
records,
records moving_sum,
1 batch_number,
rn
from tab
where rn = 1
union all
select
t.id,
t.date,
t.records,
case when c.moving_sum + t.records > 15 then t.records else c.moving_sum + t.records end,
case when c.moving_sum + t.records > 15 then c.batch_number + 1 else c.batch_number end,
t.rn
from cte c
inner join tab t on t.rn = c.rn + 1
)
select id, date, records, moving_sum, batch_number from cte order by id
The syntax for recursive common table expressions slightly varies across databases, so you might need to adapt that a little depending on your database.
Also note that if ids start at 1, and are always incrementing without gaps, you don't actually common table expression tab, and you can replace rn with id in the second common table expression.
Demo on DB Fiddle:
id | date | records | moving_sum | batch_number
-: | :--------- | ------: | ---------: | -----------:
1 | 2019-03-28 | 5 | 5 | 1
2 | 2019-03-29 | 5 | 10 | 1
3 | 2019-03-30 | 5 | 15 | 1
4 | 2019-03-28 | 2 | 2 | 2
5 | 2019-03-12 | 1 | 3 | 2
6 | 2019-03-28 | 12 | 15 | 2
7 | 2019-03-12 | 1 | 1 | 3

Group by similar number SQL (oracle sql)

I would like to find the number of sales that have a similar purchase value from the following table:
sale_number | value
------------+-------
1 | 10
2 | 11
3 | 21
4 | 30
A vanilla group by statement groups by exact value:
select count(sale_number), value from table group by value
Would give:
count(sale_number) | value
------------+-------
1 | 10
1 | 11
1 | 21
1 | 30
Is it possible to group by inexact numbers with a threshold (say +/- 10%)? Giving the desired result:
count(sale_number) | value
------------+-------
2 | 10
2 | 11
1 | 21
1 | 30
You can do what you want with a correlated subquery:
select t.*,
(select count(*)
from t t2
where t2.value >= t.value * 0.9 and
t2.value <= t.value * 1.1
) as cnt
from t;

query to count occurances of aparticular column value

Let's say I have a table with the following value
1
1
1
2
2
2
3
3
3
1
1
1
2
2
2
I need to get an out put like this, which counts each occurances of a
particular value
1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3
1 1
1 2
1 3
2 1
2 2
2 3
NB: This is a sample table Actual table is a complex table with lots of rows and columns and query contains some more conditions
If the number repeats over different "islands" then you need to calculate a value to maintain those islands first (grpnum). That first step can be undertaken by subtracting a raw top-to-bottom row number (raw_rownum) from a partitioned row number. That result gives each "island" a reference unique to that island that can then be used to partition a subsequent row number. As each order by can disturb the outcome I find it necessary to use individual steps and to pass the prior calculation up so it may be reused.
SQL Fiddle
MS SQL Server 2014 Schema Setup:
CREATE TABLE Table1 ([num] int);
INSERT INTO Table1 ([num])
VALUES (1),(1),(1),(2),(2),(2),(3),(3),(3),(1),(1),(1),(2),(2),(2);
Query 1:
select
num
, row_number() over(partition by (grpnum + num) order by raw_rownum) rn
, grpnum + num island_num
from (
select
num
, raw_rownum - row_number() over(partition by num order by raw_rownum) grpnum
, raw_rownum
from (
select
num
, row_number() over(order by (select null)) as raw_rownum
from table1
) r
) d
;
Results:
| num | rn | island_num |
|-----|----|------------|
| 1 | 1 | 1 |
| 1 | 2 | 1 |
| 1 | 3 | 1 |
| 2 | 1 | 5 |
| 2 | 2 | 5 |
| 2 | 3 | 5 |
| 1 | 1 | 7 |
| 1 | 2 | 7 |
| 1 | 3 | 7 |
| 3 | 1 | 9 |
| 3 | 2 | 9 |
| 3 | 3 | 9 |
| 2 | 1 | 11 |
| 2 | 2 | 11 |
| 2 | 3 | 11 |
SQL Server provide row_number() function :
select ID, ROW_NUMBER() OVER (PARTITION BY ID ORDER BY ID) RN FROM <TABLE_NAME>
EDIT :
select * , case when (row_number() over (order by (select 1))) %3 = 0 then 3 else
(row_number() over (order by (select 1))) %3 end [rn] from table
I think there is a problem with your sample, in that you have an implied order but not an explicit one. There is no guarantee that the database will keep and store the values the way you have them listed, so there has to be some inherent/explicit ordering mechanism to tell the database to give those values back exactly the way you listed.
For example, if you did this:
update test
set val = val + 2
where val < 3
You would find your select * no longer comes back the way you expected.
You indicated your actual table was huge, so I assume you have something like this you can use. There should be something in the table to indicate the order you want... a timestamp, perhaps, or maybe a surrogate key.
That said, assuming you have something like that and can leverage it, I believe a series of windowing functions would work.
with rowed as (
select
val,
case
when lag (val, 1, -1) over (order by 1) = val then 0
else 1
end as idx,
row_number() over (order by 1) as rn -- fix this once you have your order
from
test
),
partitioned as (
select
val, rn,
sum (idx) over (order by rn) as instance
from rowed
)
select
val, instance, count (1) over (partition by instance order by rn)
from
partitioned
This example orders by the way they are listed in the database, but you would want to change the row_number function to accommodate whatever your real ordering mechanism is.
1 1 1
1 1 2
1 1 3
2 2 1
2 2 2
2 2 3
3 3 1
3 3 2
3 3 3
1 4 1
1 4 2
1 4 3
2 5 1
2 5 2
2 5 3

Select all rows after sum of field reach specific number

I have table like below
ID | Name | Value
---+------+-------
1 | X | 10
2 | y | 15
3 | z | 3
4 | A | 20
5 | B | 6
I want to select all rows that comes after sum(Value) reach specific number
Examples :-
If that specific number is 11, the result set will be:
2 | y | 15
3 | z | 3
4 | A | 20
5 | B | 6
If that specific number is 25, the result set will be
3 | z | 3
4 | A | 20
5 | B | 6
If that specific number is 30, the result set will be
4 | A | 20
5 | B | 6
If that specific number is 50, the result set will be
5 | B | 6
You could use this correlated subquery approach to calculate running totals:
declare #value int
set #value = 11
;WITH CTE AS
(
SELECT t.*,
SumBefore = (SELECT SUM(Value)
FROM dbo.TableName t2
WHERE t2.ID <= t.ID)
FROM TableName t
)
SELECT CTE.*
FROM CTE
WHERE SumBefore > #value
DEMO
You can use this simple query (If you have SQL Server 2008+):
SELECT ID, Name, Value
FROM (
SELECT *
, SUM(Value) OVER (ORDER BY ID) As SumNow
FROM yourTable) t
WHERE
(SumNow > ?);
[SQL Fiddle Demo]
For older version of SQL Servers you can use this query:
SELECT ID, Name, Value
FROM yourTable t
WHERE
((SELECT SUM(Value)
FROM yourTable ti
WHERE ti.ID <= t.ID) > ?);
[SQL Fiddle Demo]