Author |
Topic |
ch9862
Yak Posting Veteran
76 Posts |
Posted - 2007-02-02 : 15:45:44
|
I have a table that holds events (ID, Type, Source, Dte).For each ID, I'd like to find three pieces of information:- Type (RType) for the record with Source = 'R'- Type (NonRF) for the most recent record with Source <> 'R' and Type='F'- Type (NonRNonF) for the most recent record with Source <> 'R' and Type<>'F'There will be at the most one record with Source='R', and 0 or more with Source<>'R' for each ID.In other words for the following records:declare @sample table (ID int, Type char(1), Src char(1), Dte datetime)insert @sample-- id Type Src Dteselect 1, 'F', 'R', '11/11/2000' union allselect 1, 'A', 'B', '11/12/2003' union allselect 1, 'F', 'D', '11/10/2002' union allselect 1, 'F', 'C', '11/09/2001' union allselect 2, 'F', 'H', '11/11/2000' union allselect 3, 'A', 'R', '11/11/2000' union allselect 3, 'A', 'H', '11/11/2001' union allselect 3, 'D', 'U', '11/11/2002' union allselect 4, 'W', 'R', '11/11/2000' I'd expect the following results:ID RType NonRF NonRNonF1 'F' 'F' 'A'2 '' 'F' ''3 'A' '' 'D'4 'W' '' '' How do I write query that returns such output? |
|
SwePeso
Patron Saint of Lost Yaks
30421 Posts |
Posted - 2007-02-02 : 17:15:27
|
[code]-- prepare sample datadeclare @sample table (id int, type char(1), src char(1), dte datetime)insert @sampleselect 1, 'F', 'R', '11/11/2000' union allselect 1, 'A', 'B', '11/12/2003' union allselect 1, 'F', 'D', '11/10/2002' union allselect 1, 'F', 'C', '11/09/2001' union allselect 2, 'F', 'H', '11/11/2000' union allselect 3, 'A', 'R', '11/11/2000' union allselect 3, 'A', 'H', '11/11/2001' union allselect 3, 'D', 'U', '11/11/2002' union allselect 4, 'W', 'R', '11/11/2000'-- Show the resultSELECT s1.ID, MAX(CASE WHEN s1.Src = 'R' THEN s1.Type ELSE '' END) AS RType, MAX(CASE WHEN s1.Src <> 'R' AND s1.Type = 'F' THEN 'F' ELSE '' END) AS NonRF, ISNULL((SELECT TOP 1 s2.Type FROM @Sample AS s2 WHERE s2.ID = s1.ID AND s2.Src <> 'R' AND s2.Type <> 'F' ORDER BY s2.Dte DESC), '') AS NonRNonFFROM @Sample AS s1GROUP BY s1.IDORDER BY s1.ID[/code]Peter LarssonHelsingborg, Sweden |
 |
|
ch9862
Yak Posting Veteran
76 Posts |
Posted - 2007-02-02 : 21:04:50
|
Wait - but what if there are duplicate dates in the table? Just teasing Thanks so much for your help!I'll keep studying your answers, and maybe one day I'll stop asking easy questions . |
 |
|
SwePeso
Patron Saint of Lost Yaks
30421 Posts |
Posted - 2007-02-03 : 03:39:21
|
Duplicate are no worries.Peter LarssonHelsingborg, Sweden |
 |
|
|
|
|