简体   繁体   中英

sql query about latest date

I have these two tables.

UserProfiles(userid, attr , value)
InformationValues(attr , dateOfValue, price)

Table content:

Userprofiles for userid ='ann'

在此处输入图片说明

Informationvalues

在此处输入图片说明

Now I have to select for each attr the latest date and calculate the sum for the price for each attr the userid 'ann' has.

在此处输入图片说明

The sum price for the userid 'ann' of each attr price for the latest date would be then 3,2.

What I have so far

    select sum(iv.price * (count(distinct(u.attr)))) 
from userprofiles u , informationvalues iv
    where iv.attr = u.attr and u.userid ='ann'
 and  iv.dateofvalue = (select max(dateofvalue) from informationvalues) 

I don't know what I am missing to get the value 3.2 for the userid 'ann'.

You would need to correlate the subquery to the outer query, so it gives you the latest date per attribute rather than the overal latest date.

Also it is unclear to me why you need that computation with count(distinct ...) in the outer query.

Side note: always use modern, standard join syntax (with the on keyword) rather than implicit joins (with a comma in the from clause).

I would suggest:

select sum(iv.price) total_price 
from userprofiles u 
inner join informationvalues iv on iv.attr = u.attr   -- standard join syntax
where 
    u.userid ='ann'
    and iv.dateofvalue = (
        select max(iv1.dateofvalue) 
        from informationvalues iv1 
        where iv1.attr = iv.attr                       -- correlation
    ) 

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