我有这两个表。
UserProfiles(userid, attr , value)
InformationValues(attr , dateOfValue, price)
表内容:
userid的用户配置文件='ann'
Informationvalues
现在,我必须为每个attr选择最新日期,并计算出用户名'ann'具有的每个attr的价格总和。
那么,最新日期的每个attr价格的用户ID'ann'的总价将为3,2。
我到目前为止有什么
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)
我不知道要为用户标识“ ann”获得值3.2还是缺少什么。
您将需要将子查询相关到外部查询,因此它将为您提供最新日期每个属性,而不是总的最新日期。
也不清楚我为什么需要在外部查询中使用count(distinct ...)
进行该计算。
旁注:总是使用现代的标准联接语法(带有on
关键字),而不是隐式联接(在from
子句中带有逗号)。
我建议:
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
)