获取最新项目即使为null

时间:2016-03-01 01:05:34

标签: sql database oracle

我有三个不同的表,我试图根据下面的不同表值得到输出,但是现在它返回表列的所有字段,当我只想要最新的表时。输出应如下所示:

desire output: ╔════╦════════╦═══════╦════════════╦═════════╗ ║ id ║ value ║ name ║ sum(total) ║ version ║ ╠════╬════════╬═══════╬════════════╬═════════╣ ║ 1 ║ hola ║ peter ║ 52 ║ second ║ ║ 2 ║ hello ║ john ║ 16 ║ third ║ ║ 3 ║ privet ║ luke ║ 3 ║ first ║ ╚════╩════════╩═══════╩════════════╩═════════╝

table users ╔════╦════════╦═══════╦══╗ ║ id ║ value ║ name ║ ║ ╠════╬════════╬═══════╬══╣ ║ 1 ║ hola ║ peter ║ ║ ║ 2 ║ hello ║ john ║ ║ ║ 3 ║ privet ║ luke ║ ║ ║ 4 ║ yay ║ eli ║ ║ ╚════╩════════╩═══════╩══╝

table props ╔════╦════════╦═════════╦══╗ ║ id ║ value ║ amount ║ ║ ╠════╬════════╬═════════╬══╣ ║ 1 ║ hola ║ 40 ║ ║ ║ 2 ║ hello ║ 5 ║ ║ ║ 3 ║ privet ║ 3 ║ ║ ║ 4 ║ hello ║ 2 ║ ║ ║ 5 ║ hello ║ 9 ║ ║ ║ 6 ║ hola ║ 12 ║ ║ ╚════╩════════╩═════════╩══╝ table ranks ╔════╦════════╦═════════╦════════════╗ ║ id ║ value ║ version ║ date ║ ╠════╬════════╬═════════╬════════════╣ ║ 1 ║ hola ║ first ║ 06-20-2015 ║ ║ 2 ║ hello ║ first ║ 04-24-2015 ║ ║ 3 ║ privet ║ first ║ 02-01-2015 ║ ║ 4 ║ hello ║ second ║ 10-05-2015 ║ ║ 5 ║ hello ║ third ║ 01-03-2016 ║ ║ 6 ║ hola ║ second ║ 01-23-2016 ║ ╚════╩════════╩═════════╩════════════╝

SELECT
  users.id,
  users.value,
  users.name,
  sum(props.amount),
  ranks.version

FROM
  users
join props
on (users.value=props.value)
left join
on (users.value = ranks.value)


group by
  users.id,
  users.values,
  users.title,
  ranks.version

`

1 个答案:

答案 0 :(得分:0)

首先,如果只想要一行,请不要group by版本。使用聚合时,keep是一种有用的方法:

SELECT u.id, u.value, u.name,
       sum(p.amount),
       max(r.version) keep (dense_rank first order by r.version) as version,
       max(r.value) keep (dense_rank first order by r.version) as value
FROM users u join
     props p
     on u.value = p.value left join
     ranks r
     on u.value = r.value
GROUP BY u.id, u.values, u.title;