Jump to content

Help with a query -- limit one row per match


arenaninja

Recommended Posts

I'm using MySQL 5.5.21. I have a table, the show create statement as follows:

| feeschedule | CREATE TABLE `feeschedule` (
  `pkRateID` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `fkEquipID` int(10) unsigned NOT NULL,
  `fkInstTypeID` int(10) unsigned NOT NULL,
  `rate` decimal(6,2) NOT NULL,
  `dateOfEffect` date NOT NULL,
  PRIMARY KEY (`pkRateID`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1 |

This table records rates for a particular Equipment (fkEquipID) for different institution types (fkInstTypeID). As these are subject to change, the changes are distinguished by dateOfEffect. However, I'm having issues filtering properly. I would like to select ONLY the data matching the most recent unique fkEquipID and fkInstTypeID entry.

I tried:

 SELECT * FROM feeschedule WHERE dateOfEffect<='2012-07-27' GROUP BY fkEquipID,fkInstTypeID ORDER BY dateOfEffect DESC;

but though this does return only one column per matching fkEquipID and fkInstTypeID, it is not the most recent one.

 

Your help is greatly appreciated.

Link to comment
Share on other sites

SELECT f.fkEquipID, f.fkInstTypeID, f.rate, f.dateOfEffect
FROM feeschedule f
INNER JOIN (
    SELECT fkEquipID, fkInstTypeID, MAX(dateOfEffect) as latest
    FROM feeschedule
    GROUP BY fkEquipID, fkInstTypeID
) as x
ON f.fkEquipID = x.fkEquipID AND f.fkInstTypeID = x.fkInstTypeID AND f.dateOfEffect = x.latest

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.