0

I have a SQL table like this

id date number type
1 2022-02-02 1 DC
2 2022-02-03 20 DC
3 2022-02-03 9 DC
4 2022-03-04 2 KF

I want to sum number column with condition "type" = "DC" and last row per date.
I should get result 10 (9+1) because on date 2022-02-03 have 2 row, the last row will taken (9)

Thom A
  • 88,727
  • 11
  • 45
  • 75
  • 1
    So what's stopping you doing what you need to do? What is the difficulty you are having achieving your goal? What have you tried? Why isn't it working? What about the articles/documentation/answers you read didn't you understand? – Thom A May 09 '23 at 08:40

1 Answers1

-1

First we have to get ids that respect your conditions (type = 'DC' and max id ):

select type, max(id) as id
  from mytable
  where type = 'DC'
  group by type, date

Then we join this list with our table to get the whole row :

select sum(number)
from mytable t
join (
  select type, max(id) as id
  from mytable
  where type = 'DC'
  group by type, date
) as s on s.id = t.id

Demo here

SelVazi
  • 10,028
  • 2
  • 13
  • 29