A
A
Alexey Likhachev2014-01-22 16:07:49
SQL
Alexey Likhachev, 2014-01-22 16:07:49

SQL string comparison by dates?

There is a log table with the following logs:
id | link_id | date | value
where id is a sequence number, link_id is a link to another table, date is the record creation date, value is a value.
It is required to find the difference between the value of the last and the penultimate date for each link_id, the one itself gets something like this:

select log1.link_id,log2.link_id,log1.value,log2.value,log1.value - log2.value as diff,log1.date,log2.date
from log as log1, log as log2
where log1.link_id = log2.link_id and 
log2.date = (select max(date) from log as log3 where log3.link_id = log2.link_id) and 
log1.date = (select max(date) from log as log4 where log4.link_id = log1.link_id and log4.date = (select max(date) from log as log5 where log5.link_id = log4.link_id))

In my opinion, the logic is as follows: we display the difference between value where link_id match and where one date is the maximum, the other before the maximum

Answer the question

In order to leave comments, you need to log in

3 answer(s)
K
kirillzorin, 2014-01-23
@Playbot

Why don't you like your own version? There you only need to change the "=" to "<" in the "log4.date =" condition.

S
SabMakc, 2014-01-22
@SabMakc

For MS SQL, you can use the following query:

select link_id, sum(case NUM when 1 then [date] when 2 then [date]*(-1) else 0 end)
from (select ROW_NUMBER() over (PARTITION BY link_id order by [date]) as NUM, link_id, [date] from [log])t
group by link_id

A
Alexander, 2014-01-22
@Papagatto

@SabMakc , slightly off. We need the value difference, not [date]. And what is [date]*(-1)???
It will be correct like this:

select link_id, sum(case NUM 
                      when 1 then value 
          when 2 then value*(-1) 
          else 0 
        end)
from (select ROW_NUMBER() over (PARTITION BY link_id order by [date] desc) as NUM, link_id, value from log) t
group by link_id

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question