how do sum every Column in Sql Sevrer? [duplicate] - sql

This question already has answers here:
Calculate a Running Total in SQL Server
(15 answers)
Closed 4 years ago.
Every record amount sum into Total column
id Amount total
--------------------------------------------
1 100 100
1 50 150
1 60 210
1 10 220
2 70 290
2 10 300
Any suggestion would be very much appreciated.

You want window function :
select t.*,
sum(amount) over (order by id rows between unbounded preceding and current row) as total
from table t;

Related

SQL Get max value of n next rows

Say I have a table with two columns: the time and the value. I want to be able to get a table with :
for each time get the max values of every next n seconds.
If I want the max value of every next 3 seconds, the following table:
time
value
1
6
2
1
3
4
4
2
5
5
6
1
7
1
8
3
9
7
Should return:
time
value
max
1
6
6
2
1
4
3
4
5
4
2
5
5
5
5
6
1
3
7
1
7
8
3
NULL
9
7
NULL
Is there a way to do this directly with an sql query?
You can use the max window function:
select *,
case
when row_number() over(order by time desc) > 2 then
max(value) over(order by time rows between current row and 2 following)
end as max
from table_name;
Fiddle
The case expression checks that there are more than 2 rows after the current row to calculate the max, otherwise null is returned (for the last 2 rows ordered by time).
Similar Version to Zakaria, but this solution uses about 40% less CPU resources (scaled to 3M rows for benchmark) as the window functions both use the same exact OVER clause so SQL can better optimize the query.
Optimized Max Value of Rolling Window of 3 Rows
SELECT *,
MaxValueIn3SecondWindow = CASE
/*Check 3 rows exists to compare. If 3 rows exists, then calculate max value*/
WHEN 3 = COUNT(*) OVER (ORDER BY [Time] ROWS BETWEEN CURRENT ROW AND 2 FOLLOWING)
/*Returns max [Value] between the current row and the next 2 rows*/
THEN MAX(A.[Value]) OVER (ORDER BY [Time] ROWS BETWEEN CURRENT ROW AND 2 FOLLOWING)
END
FROM #YourTable AS A

SQL: Count rows where column value changed from previous row [duplicate]

This question already has an answer here:
increment row number when value of field changes in Oracle
(1 answer)
Closed 2 years ago.
Suppose I have Oracle or Postgresql database.
ID IdExample OrderByColumn What I want
---------- ---------- ---------- ----------
1 1 1300 1
2 1 2450 1
3 2 5000 2
4 2 4800 2
5 1 5100 3
6 1 6000 3
7 4 7000 4
8 1 8000 5
How do count the changes that are in idExample, data is sorted by OrderByColumn
I need output new column that is represented by "what I want"
pay attention to "1" in IdExample. It repeats but I wants to iterate.
The query should execute quickly with the table having tens of thousands of records.
THANKS
You need to use lag and sum analytical function as follows:
Select t.*,
sum(case when lg is null or lg <> idexample then 1 else 0 end)
over (order by id) as result
from
(Select t.*,
lag(idexample) over (order by id) as lg
From your_table t) t

SQL Server - Add or Subtract from Previous Value

I'm trying to get the balance from this data
Date Logged Closed
-------------- ----------- -----------
1-Jan-2016 0 0
2-Jan-2016 8 7
3-Jan-2016 8 8
4-Jan-2016 25 11
5-Jan-2016 20 16
6-Jan-2016 14 13
7-Jan-2016 10 12
8-Jan-2016 9 7
9-Jan-2016 12 12
10-Jan-2016 3 4
The expected output is
Date Logged Closed Balance
-------------- ----------- ----------- ----------
1-Jan-2016 0 0 0
2-Jan-2016 8 7 1
3-Jan-2016 8 8 1
4-Jan-2016 25 11 15
5-Jan-2016 20 16 19
6-Jan-2016 14 13 20
7-Jan-2016 10 12 18
8-Jan-2016 9 7 20
9-Jan-2016 12 12 20
10-Jan-2016 3 4 27
The formula is BALANCE =
PREVIOUSBALANCE + LOGGED - CLOSED.
Example formula :
Jan 5 Balance (15) = 1(prevBalance) + 25(currentLogged) - 11(currentClosed)
I've tried this formula but does not get anywhere close to the desired result.
WITH CTE AS (
SELECT
rownum = ROW_NUMBER() OVER (ORDER BY Date),
Date, Logged, Closed
FROM Table
)
SELECT
(prev.Logged - prev.Closed)+ (a.Logged-a.Closed) as [Balance]
FROM CTE
LEFT JOIN CTE prev ON prev.rownum = CTE.rownum - 1
Other references used
SQL Server - Calculate current row value using previous row value
http://blog.sqlauthority.com/2013/09/22/sql-server-how-to-access-the-previous-row-and-next-row-value-in-select-statement/
You can do this using Window function sum.
Try this:
select
t.*,
sum(logged - closed) over (order by date) balance
from your_table t;
The problem of your answer is the Balanced of the previous row is not available when you calculate (SQL-Server 's All-at-once principle). Your question has a hidden requirement of calculating sum of all the previous rows, ordered by date.
Try this (only applied for SQL Server 2012 and beyond)
SELECT
[Date], Logged, Closed,
SUM(Logged) OVER (ORDER BY [Date] ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
- SUM (Closed) OVER (ORDER BY [Date] ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS Balance
FROM
<<Table>>
For previous version:
SELECT
t.[Date], t.Logged, t.Closed, sub.L - sub.C AS Balanced
FROM
<<Table>> t
CROSS APPLY ( SELECT SUM(Logged) AS L, SUM(Closed) AS c FROM <<Table>> WHERE [Date] <= t.[Date]) AS sub

min value sql query [duplicate]

This question already has answers here:
row with minimum value of a column
(7 answers)
Closed 6 years ago.
I have a data with three columns as below:
lic_plt_id qty prod_qty
--------------------------------
123456 3 44556
345567 50 44556
098765 13 44556
result required is where qty is minimum with below detail.
lic_plt_id qty prod_qty
----------------------------
123456 3 44556
SELECT TOP 1 *
FROM Tablename
ORDER BY qty
this will order the table by qty and then selects the first one which is the lowest number.

SQL involving MAX of two colums and Group BY [duplicate]

This question already has answers here:
Select first row in each GROUP BY group?
(20 answers)
Closed 7 years ago.
So... i got a table like this:
id group number year
1 1 1 2000
2 1 2 2000
3 1 1 2001
4 2 1 2000
5 2 2 2000
6 2 1 2001
7 2 2 2001
8 2 3 2001
And i need to select the bigger number of the bigger year for each group. So i expect the result of the exemple to be:
3 1 1 2001
8 2 3 2001
any ideias?
OBS: using Postgres
SELECT *
FROM (
SELECT *,
row_number() over (partition by "group" order by "year" desc, "number" desc ) x
FROM table1
) x
WHERE x = 1;
demo: http://sqlfiddle.com/#!15/cd78e/2
If it's just certain rows you want to get you can use DISTINCT. If you want different maximums on the same rows you could use GROUP BY
SELECT DISTINCT ON ("group") * FROM tbl
ORDER BY "group", year DESC, id DESC;