Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
Author |
Topic |
Faiyth
Starting Member
19 Posts |
Posted - 2008-03-21 : 19:05:38
|
Alright here's what I'm trying to do. I've been searching all day for the solution and can't seem to figure it out...I have 3 tables. Table1 has all the Restaurants in it, Table2 has all the Inspection Scores for those Restaurants, Table3 has all the Inspection Details for those Restaurants.TABLE1-----------Estab ID - Estab Name - Estab City1 - Coffee Palace - Portland2 - Coffee Fort - Tanland3 - Hotdogs Galore - CelevenTABLE2------------------Insp ID - Estab ID - Insp Date - Insp Score - Insp Type1 - 3 - 03/01/08 - 100 - F2 - 3 - 02/01/08 - 90 - A3 - 2 - 03/21/08 - 86 - F4 - 1 - 02/11/08 - 71 - CTABLE3-------------Inspection Type - Inspection Type DescF - FullA - PartialC - ClosedBecause restaurant 3 has been inspected more then once (it's been inspected twice) In my results I'm getting that restaurant twice. What I want is all the records in Table1 and then the newest score and matching Inspection Type. I don't want duplicates of the information in Table1. Here's my code so far: SELECT t1.[Estab ID] eid, [Estab Name] as ename, [Estab City] as ecity, [Insp Date] as idate, [Insp Score] as iscore, [Inspection Type Desc] as itype FROM Table1 t1, Table2 t2, Table3 t3 WHERE t1.[Estab ID]=t2.[Estab ID] and t2.[Inspection Type]=t3.[Inspection Type] |
|
tkizer
Almighty SQL Goddess
38200 Posts |
Posted - 2008-03-21 : 19:36:53
|
Use a GROUP BY and the MAX aggregate function.Tara KizerMicrosoft MVP for Windows Server System - SQL Serverhttp://weblogs.sqlteam.com/tarad/ |
 |
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2008-03-23 : 12:41:07
|
[code]SELECT t1.[Estab ID], t1.[Estab Name], t1.[Estab City], t2.[Insp Date], t2.[Insp Score], t3.[Inspection Type Desc]FROM TABLE1 t1INNER JOIN TABLE2 t2ON t2.[Estab ID]=t1.[Estab ID]INNER JOIN (SELECT [Estab ID],MAX([Insp Date]) AS MaxInspDate FROM TABLE2 GROUP BY [Estab ID])tmpON tmp.[Estab ID]=t2.[Estab ID]AND tmp.MaxInspDate=t2.[Insp Date]INNER JOIN TABLE3 t3ON t3.[Inspection Type]=t2.[Insp Type][/code] |
 |
|
|
|
|
|
|