Domanda

I have a big problem that I've been trying to tackle. Reading older similar issues hasn't been fruitful.

My table has columns [id], [parentid], [data1], [data2] etc. There are some cases where only one record has same [parentid] and others have 2-10.

I would like to group by [parentid] and print out all data of the record which has maximum [id]. So I would only get all the "latest" details for the records which share the same [parentid] number.

I hope this is comprehensible goal in any way :).

I've also tried to tackle this in Crystal Reports XI and Qlikview 11 without major success.

Thanks in advance for any help!

È stato utile?

Soluzione

Can values in your ID column be reused? If no, then juergen's answer will work. If they can be reused, you will need to use the same table twice in your query, once to get the max id for each parent id, and once to get the row for each max id/parent id. Like so:

select
t1.*
from aTable t1,
(select parentid, max(id) as id
 from aTable group by parentid) t2
where t1.id = t2.id
and t1.parentid = t2.parentid

SQLFIddle!

Altri suggerimenti

select * from your_table
where id in 
(
  select max(id)
  from your_table
  group by parentid
)

A solution with would be:

Script:

Table:
Load id, 
     parentid, 
     d1, 
     d2
inline
[
  id, parentid, d1, d2
  1, 0,   Hep, 01-04-2010
  2, 1,   Hap, 09-04-2010
  3, 1,   Hup, 10-10-2012
  4, 2,   Bep, 01-12-2009
  5, 4,   Ceg, 02-10-2010
  6, 4,   Pen, 05-10-2009
  7, 4,   Heg, 01-10-2009
  8, 4,   Ran, 08-01-2010
];

Then I added the fields id and parentid to the dashboard. To calulate the results use a table diagram where parentid is the dimension. Add a formula

=max(id)

and name it 'max(id)'

Then you get the following result:

enter image description here

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top