Given this data:
Bolt_Table
:
PID | UNIQ ID | GROUP_ID | Distance |
---|---|---|---|
PID_24_2225 | 14 | 13 | 1141 |
PID_5_1444E | 3214 | 13 | 652 |
PID_5_14454 | 3152 | 13 | 802 |
PID_24_2225 | 15 | 14 | 1141 |
PID_5_14454 | 3151 | 14 | 802 |
PID_5_1444E | 3213 | 14 | 652 |
PID_26_21FC | 536 | 2300 | 597 |
PID_5_13388 | 4121 | 2300 | 620 |
PID_5_13382 | 4169 | 2300 | 802 |
This is the desired result:
PID | UNIQ_ID | GROUP_ID | Distance |
---|---|---|---|
PID_5_1444E | 3214 | 13 | 652 |
PID_5_1444E | 3213 | 14 | 652 |
PID_5_13388 | 4121 | 2300 | 620 |
Explanation:
1st Record:
@Group ID = 13
,Get the similar PID
PID_5_1444E
andPID_5_14454
- compare the corresponding distances minimum of (652 and 802). Since 652 is the least, the corresponding PID: " PID_5_1444E " should be retained, hence record 1 of the desired table
What would be the query for SQL? (Microsoft Access)
I tried using LIKE, MID(String,1,4), GROUP BY & HAVING but nothing seems to work. How should I make the query for this?
The closest one I got is when I force to do the judging under a hard coded GROUP_ID,I would like to do it FOR EACH GROUP_ID
SELECT TOP 1 PERCENT PID, UNIQ_ID, GROUP_ID, Distance
FROM
(
SELECT
a.PID, a.UNIQ_ID, a.GROUP_ID, ID, a.Distance,
(select count(PID) as counter from Bolt_Table where GROUP_ID = a.GROUP_ID and LEFT(PID, 9) = LEFT(a.PID, 9)) as counter from Bolt_Table a WHERE a.GROUP_ID = 13
)
where counter > 1
order by Distance