简体   繁体   中英

how do I query sql for a Sum value + latest record date

i have students table and i need to collect the value by calculating the formula.

Date,Person name,status,value,mark1,mark2
01/08/2020,Andrew,New,10,32,45
07/08/2020,Andrew,New,10,44,44
22/08/2020,Andrew,New,10,55,34
15/09/2020,Mirandz,New,11,44,44
22/09/2020,Mirandz,New,11,77,55
07/09/2020,Lucaz,New,54,66,55
30/09/2020,Lucaz,New,54,23,55

here i would like to do sum(mark1)+sum(mark2)+value(where date is maximum) based on Person name

Need help on write the SQL Query to get the summarized value for latest value add with existing column values.

32+44+55+45+44+34+10

I tried with below query

Select SUM(mark1)+SUM(Mark2)+Value from table where MAX(date)

am totally new to sql server. any help will much appreciated.

The values are constant in your sample data per name, so you can use:

select name, sum(mark1) + sum(mark2) + value
from students
group by name, value;

If the value were not constant, you could implement the logic in a variety of ways. One uses first_value() :

select name, sum(mark1) + sum(mark2) + most_recent_value
from (select s.*,
             first_value(value) over (partition by name order by date desc) as most_recent_value
      from students s
     ) s
group by name, most_recent_value;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM