sql 查询最近日期
sql query about latest date
我有这两张表。
UserProfiles(userid, attr , value)
InformationValues(attr , dateOfValue, price)
Table内容:
userid ='ann'
的用户配置文件
信息值
现在我必须 select 每个属性的最新日期,并计算用户 ID 'ann' 拥有的每个属性的价格总和。
最后日期的每个 attr 价格的 userid '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)
我不知道我缺少什么来获取用户 ID '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
)
我有这两张表。
UserProfiles(userid, attr , value)
InformationValues(attr , dateOfValue, price)
Table内容:
userid ='ann'
的用户配置文件信息值
现在我必须 select 每个属性的最新日期,并计算用户 ID 'ann' 拥有的每个属性的价格总和。
最后日期的每个 attr 价格的 userid '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)
我不知道我缺少什么来获取用户 ID '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
)