How to Sum the Total salary column by adding the Salary Column - sql-server

Cola
Salary
TotalSalary
A
100
100
B
200
300
C
300
600

You can use the sum() window function to get a running total:
select Cola,
Salary,
Sum(Salary) over(order by Cola rows unbounded preceding) as TotalSalary
from yourtable;
Fiddle

Related

select max value in each 5 rows

My total rows are variable and not fixed , So there are N rows and I want to separate each 5 rows as a group and select the max value of price in following table in SQL.
Date Price
20170101 100
20170102 110
20170103 90
20170105 80
20170109 76
20170110 50
20170111 55
20170113 80
20170115 100
20170120 99
20170121 88
20170122 98
20170123 120
So in first 5 group the max price is 110 , and second group is 100, and last group max price is 120.
Use a common table expression to group them.
WITH CTE AS (SELECT RANK() OVER (ORDER BY Date) AS Rank, Price
FROM yourtable)
SELECT (Rank - 1) / 5 AS GroupedDate, MAX(Price) AS MAXPRICE
FROM CTE
GROUP BY ((Rank - 1) / 5);
Output
GroupedDate MAXPRICE
0 110
1 100
2 120
SQL Fiddle: http://sqlfiddle.com/#!6/b5857/3/0
You can use row_number as below
;With cte as (
Select *, Bucket = Sum(RowN) over(Order by [date]) from (
Select *, RowN = case when row_number() over(order by [date]) % 5 = 0 then 1 else 0 end from #data1
) a
) Select top (1) with ties [Date], [Price]
from cte
order by row_number() over (partition by Bucket order by Price desc)
You could use:
SELECT grp, MAX(Price) AS price
FROM (SELECT *, ROW_NUMBER() OVER(ORDER BY DATE) / 5 AS grp FROM tab) sub
GROUP BY grp;
-- OUTPUT
grp price
0 110
1 100
2 120
Rextester Demo
*assuming that date is unique
EDIT:
As in something like : 20170101 - 20170109 110
SELECT
CONVERT(VARCHAR(8),MIN(DATE),112) + '-' + CONVERT(VARCHAR(8),MAX(date),112)
, MAX(Price) AS price
FROM (SELECT *, (ROW_NUMBER() OVER(ORDER BY DATE) ) / 5 AS grp FROM tab) sub
GROUP BY grp;
Output:
20170101-20170105 110
20170109-20170115 100
20170120-20170123 120
Rextester Demo2

sequence Rank in query

I would like to get sequence number in mssql. Please see below.
There is a table.
UserID Score TeamID
------------------------------
1 100 1
2 200 1
3 500 2
4 600 2
5 700 2
6 1000 3
I would like to sort by total score group by team. see below
RankID UserID Score TeamID TotalScore
-----------------------------------------------------------
1 3 500 2 1800
1 4 600 2 1800
1 5 700 2 1800
2 6 1000 3 1000
3 1 100 1 300
3 2 200 1 300
I want to code only one sql query. Help me someone how can I do this? Thanks.
This should work:
;WITH TotalScore AS (
SELECT UserID, Score, TeamID,
SUM(Score) OVER (PARTITION BY TeamID) AS TotalScore
FROM mytable
)
SELECT DENSE_RANK() OVER (ORDER BY TotalScore DESC) AS RankID,
UserID, Score, TeamID, TotalScore
FROM TotalScore
ORDER BY TotalScore DESC, Score
The Common Table Expression used calculates the total score per TeamID using windowed version of SUM. Using DENSE_RANK together with this calculated field we can easily generate the required RankID.
You can try this
SELECT
RANK() OVER(ORDER BY i.TotalScore DESC) AS RankID
,A.*
FROM
(
SELECT
UserID
,Score
,TeamID
,(SELECT SUM(Score) FROM yourTable tb2 WHERE tb2.TeamID = tb1.TeamID) AS TotalScore
FROM yourTable tb1
) A
ORDER BY A.TotalScore DESC
Have a Try with below,
Select DENSE_RANK() over(Order by (Select Sum(Score) from #tablename V where V.TeamID=T.TeamID ) desc )RankID
,*,
Sum(Score) over(Partition by TeamID) TotalScore from #tablename T
order by DENSE_RANK() over(Order by (Select Sum(Score) from #tablename V where V.TeamID=T.TeamID ) desc )
Dense Rank in the 'Order by' to sort the results by RANK Id and the same is used in Select statement, Subquery in the Dense Rank will rank based on the sum(Score) for a TeamID

How do I achieve addition of each rows in T-SQL?

I have my data which may be around 50 records for each address:
Id AddressId Income Expense Revenue
----------------------------------------
1 1 100 200 300
2 1 150 20 200
3 1 160 80 800
4 1 50 90 200
5 1 600 700 500
Now I need my data in the following format:
Ids Count Income Expense Revenue
---------------------------------------
1 1 100 200 300
1,2 2 250 220 500
1,2,3 3 410 300 1300
1,2,3,4 4 460 390 1500
1,2,3,4,5 5 1060 1090 2000
Every row is being added one after another.
For example:
The Ids 1,2 is a sum of Id 1 and 2
The Ids 1,2,3 is a sum of Id 1 and 2 and 3 and so on
I don't need the Ids column, the only thing I need is the sum
You could use STUFF, ROW_NUMBER() OVER(), and SUM() OVER() like this
DECLARE #SampleData AS TABLE
(
Id int,
AddressId int,
Income int,
Expense int,
Revenue int
)
INSERT INTO #SampleData
VALUES
( 1, 1, 100, 200, 300),
( 2, 1, 150, 20 , 200),
( 3, 1, 160, 80 , 800),
( 4, 1, 50 , 90 , 200),
( 5, 1, 600, 700, 500)
SELECT
STUFF(
(
SELECT ',' + CAST(sd1.Id AS varchar(10))
FROM #SampleData sd1
WHERE sd1.AddressId = sd.AddressId AND sd1.Id <= sd.Id
FOR XML PATH('')
),
1,1,'') AS Ids,
Row_number() OVER(PARTITION BY sd.AddressId ORDER BY sd.Id) AS Count,
sum(sd.Income) OVER(PARTITION BY sd.AddressId ORDER BY sd.Id) AS Income,
sum(sd.Expense) OVER(PARTITION BY sd.AddressId ORDER BY sd.Id) AS Expense,
sum(sd.Revenue) OVER(PARTITION BY sd.AddressId ORDER BY sd.Id) AS Revenue
FROM #SampleData sd
ORDER BY sd.AddressId, sd.Id
Demo link: http://rextester.com/HRIWH92029
Note: The last revenue should be 2000 instead of 1600
If you're using SQL server 2012 and above,
please use below query for the sum up the previous rows
Select ID,
count(*) OVER (PARTITION by AddressID
ORDER BY ID
ROWS BETWEEN unbounded PRECEDING AND current row) as[Count],
sum(Income) OVER (PARTITION by AddressID
ORDER BY ID
ROWS BETWEEN unbounded PRECEDING AND current row) Income,
sum(Expense) OVER (PARTITION by AddressID
ORDER BY ID
ROWS BETWEEN unbounded PRECEDING AND current row)Expense,
sum(Revenue) OVER (PARTITION by AddressID
ORDER BY ID
ROWS BETWEEN unbounded PRECEDING AND current row) Revenue from TableName
If you're using SQL server 2008 and below, please use below query for the sum up the previous rows.
Select ID, (select count(*) from Tablename A where A.Id<=Tablename.ID)[Count],
(select sum(Income) from Tablename A where A.Id<=Tablename.ID) Income, (select
sum(Expense) from Tablename A where A.Id<=Tablename.ID) Expense, (select
sum(Revenue) from Tablename A where A.Id<=Tablename.ID) Revenue from Tablename

SQL Server query should return max value records

I have table like this:
id_Seq_No emp_name Current_Property_value
-----------------------------------------------
1 John 100
2 Peter 200
3 Pollard 50
4 John 500
I want the max record value of particular employee.
For example, John has 2 records seq_no 1, 4. I want 4th seq_no Current_Property_Value in single query.
Select
max(id_Seq_No)
from
t1
where
emp_name = 'John'
To get the Current_Property_value, just order the results by id_Seq_No and get the first one:
SELECT
TOP 1 Current_Property_value
FROM
table
WHERE
emp_name = 'John'
ORDER BY
id_Seq_No DESC
this will give highest for all tied employees
select top 1 with ties
id_Seq_No,emp_name,Current_Property_value
from
table
order by
row_number() over (partition by emp_name order by Current_Property_value desc)
You can use ROW_NUMBER with CTE.
Query
;WITH CTE AS(
SELECT rn = ROW_NUMBER() OVER(
PARTITION BY emp_name
ORDER BY id_Seq_No DESC
), *
FROM your_table_name
WHERE emp_name = 'John'
)
SELECT * FROM CTE
WHERE rn = 1;

SQL query to find the top rows in SQL Server

In SQL Server, I am trying to get the top 5 salaries.
I have salaries like
5000
5000
4500
4500
3000
2000
1000
500
400
and I'd like to get
5000
5000
4500
4500
3000
2000
1000
SELECT TOP 5 salary FROM your_table
ORDER BY salary DESC
If you want to get the top 5 distinct salaries (no matter how many times the same amount might show up), you need to use the DENSE_RANK() ranking function and a CTE to achieve this:
DECLARE #salaries TABLE (salary DECIMAL(18,4))
INSERT INTO #salaries VALUES(5000)
INSERT INTO #salaries VALUES(5000)
INSERT INTO #salaries VALUES(4500)
INSERT INTO #salaries VALUES(4500)
INSERT INTO #salaries VALUES(3000)
INSERT INTO #salaries VALUES(2000)
INSERT INTO #salaries VALUES(1000)
INSERT INTO #salaries VALUES(500)
INSERT INTO #salaries VALUES(400)
;WITH SalariesRanked AS
(
SELECT
Salary,
SalaryNumber = DENSE_RANK() OVER(ORDER BY Salary DESC)
FROM
#salaries
)
SELECT salary
FROM SalariesRanked
WHERE SalaryNumber <= 5
This results in an output like this:
salary
5000.0000
5000.0000
4500.0000
4500.0000
3000.0000
2000.0000
1000.0000
select salary
from
(
select salary,
dense_rank() over(order by salary desc) as rn
from YourTable
) as T
where rn <= 5
Try on SE-Data
Have a look at using TOP (Transact-SQL)
SELECT TOP 5 Salary
FROM [Table]
GROUP BY Salary
ORDER BY Salary DESC
You need to group the query to avoid the duplicated salaries.

Resources