SQL - Add value with previous row only - sql

I have a table named myvals with the following fields:
ID number
-- -------
1 7
2 3
3 4
4 0
5 9
Starting on 2nd row, I would like to add the number with the previous row number. So, my end result would look like this
ID number
-- ------
1 7
2 10
3 7
4 4
5 9

You could use the LAG analytic function
SELECT Id, number + LAG(number,1,0) OVER (ORDER BY Id) FROM table

First thing's first. You can't add to null to ID 1 must have a value.

create table #temp
(
month_type datetime,
value int
)
insert into #temp
Select '2015/01/01',1
union
Select '2015/02/01',2
union
Select '2015/03/01',3
union
Select '2015/04/01',4
SELECT t.value,t1.value,(t.value+t1.value)/2 FROM #temp t1
left join #temp t on t.month_type=Dateadd(MONTH,-1,t1.month_type)

Related

How to sum values in a column based on values in a different column SQL

For example, lets say I have
id
values
1
10
1
12
1
10
2
2
2
5
2
4
then i would want sql to return
id
values
1
32
2
11
This is very basic sql.
select id, sum(values) as values
from foo
group by id
Select ID,sum(values)
From table
Group by ID;

SQL Server : create a column by summing another column

I am trying to create a new column in my table by summing up values from another column within the same table
Here is an example:
Header 1 Header 2 Header 3 (new column)
------------------------------------------------------
1 1 1 1
2 2 6 12
3 2 6 12
4 3 4 8
5 3 4 8
I want the sum to be done categorically based on the categories in Header 2, with the values of Header 3.
What SQL code can I use for this?
You need window function :
select t.*, sum(header3) over (partition by header2) as newcol
from table t;
You can also use cte structure like:
;with cte (header2,Total) as (
select header2,sum(header3) as Total
from table
group by header2
)
select t.*,cte.Total
from table t
inner join cte on cte.header2 = t.header2
You can also use
SELECT T1.*,
(SELECT SUM(Header3) FROM T WHERE Header2 = T1.Header2) ExpectedResults
FROM T T1;

Select last complete block of rows

I have data similar to
ID Position
1 1
2 2
3 3
4 1
5 2
6 3
7 1
8 2
and I want to select the last set of rows that contain all positions, 1 through 3. By last I mean the set of rows with the highest value in the ID column. The desired result is
ID Position
4 1
5 2
6 3
How can i achieve this?
You can use this method, which find the last ID where the Position is 3, and gets the two rows preceding that. This assumes Position is sequential as it is in the sample data.
declare #table table (ID int identity(1,1), Position int)
insert into #table
values
(1),(2),(3),(1),(2),(3),(1),(2)
select top 3
*
from #table
where ID <=(
select max(ID)
from #table
where Position = 3)
order by ID desc
Or you could do this with an AND in your WHERE clause. I would store the ID as a variable so you only have to do the aggregation once though.
declare #id int = ( select max(ID)
from #table
where Position = 3)
select *
from #table
where ID <= #id
and ID >= #id - 2
order by ID

Get offset of a row after performing sort operation in sql

I am using SQLite database.
Suppose I have rows with IDs 1 to 50. Then I perform select and order by operation.
Say, the result is IDs : 6,3,5,2,9,12,1,34,45,15.
Now, I want to know the offset of a particular row with given ID in the above result.e.g. offset of ID 1 is 6.
Can I do this in a single query?
put the query of ordered result into a subquery and use count(*) and check the id sequence:
Example:
SCHEMA:
CREATE TABLE tbl ("id" INTEGER,"val" INTEGER);
INSERT INTO tbl ("id","val")
VALUES
(12,6),(1,7),(34,8),(6,1),(9,5),
(45,9),(15,10),(3,2),(5,3),(2,4);
QUERY:
select id,(
select count(*)
from (
select id,val
from tbl order by val
) b
where a.val >= b.val)-1 as offset
from tbl a
order by offset
RESULT:
id offset
6 0
3 1
5 2
2 3
9 4
12 5
1 6
34 7
45 8
15 9
SQLFIDDLE DEMO

Is there a way to update groups of rows with separate incrementing values in one query

Lets say you have the following table:
Id Index
1 3
1 1
2 1
3 3
1 5
what I would like to have is the following:
Id Index
1 0
1 1
2 0
3 0
1 2
As you might notice, the goal is for every row where Id is the same, to incrementally update the Index column, starting from zero.
Now, I know this is fairly simple with using cursors, but out of curiosity is there a way to do this with single UPDATE query, somehow combining with temp tables, common table expressions or something similar?
Yes, assuming that the you don't really care about the order of the values for the new index values. SQL Server offers updatable CTEs and window functions that do exactly what you want:
with toupdate as (
select t.*, row_number() over (partition by id order by (select NULL)) as newindex
from table t
)
update toupdate
set index = newindex;
If you want them in a specific order, then you need another column to specify the ordering. The existing index column doesn't work.
With Row_number() -1 and CTE you can write as:
CREATE TABLE #temp1(
Id int,
[Index] int)
INSERT INTO #temp1 VALUES (1,3),(1,1),(2,1),(3,3),(1,5);
--select * from #temp1;
With CTE as
(
select t.*, row_number() over (partition by id order by (select null))-1 as newindex
from #temp1 t
)
Update CTE
set [Index] = newindex;
select * from #temp1;
Demo
I'm not sure why you would want to do this really, but I had fun figuring it out!
This solution relies on your table having a primary key for the self join... but you could always create an auto inc index if none exists and this is a one off job... This will also have the added benefit of getting you to think about the precise ordering of this you want... as currently there is no way of saying which order [ID] will get [Index] in.
UPDATE dbo.Example
SET [Index] = b.newIndex
FROM dbo.Example a
INNER JOIN (
select
z.ID,
z.[Index],
(row_number() over (partition by ID order by (select NULL))) as newIndex
from Example z
) b ON a.ID = b.ID AND a.[Index]=b.[Index] --Is this a unique self join for your table?.. no PK provided. You might need to make an index first.
Probably, this is what you want
SELECT *,RANK() OVER(PARTITION BY Id ORDER BY [Index])-1 AS NewIndex FROM
(
SELECT 1 AS Id,3 [Index]
UNION
SELECT 1,1
UNION
SELECT 2,1
UNION
SELECT 3,3
UNION
SELECT 1,5
) AS T
& the result will come as
Now if you want to update the table then execute this script
UPDATE tblname SET Index=RANK() OVER(PARTITION BY t.Id ORDER BY t.[Index])-1
FROM tblname AS t
In case I am missing something or any further assistance is required please let me know.
CREATE TABLE #temp1(
Id int,
Value int)
INSERT INTO #temp1 VALUES (1,2),(1,3),(2,3),(4,5)
SELECT
Id
,Value
,ROW_NUMBER() OVER (PARTITION BY Id ORDER BY Id) Id
FROM #temp1
Start with this :)
Gave me results like
Id Value Count
1 2 1
1 3 2
1 2 3
1 3 4
1 2 5
1 3 6
1 2 7
1 3 8
2 3 1
2 4 2
2 5 3
2 3 4
2 4 5
2 5 6
2 4 7
2 5 8
2 3 9
2 3 10
3 4 1
4 5 1
4 5 2
4 5 3
4 5 4