I`m new to sql and have been stuck on the following issue for almost a day now:
I have two tables that I pull values from, devices and devices_LOG. I need to display all the devices_LOG entries where devices.status = ‘1’ AND I need them to be unique (ie I only want to see one devices_LOG entry for each device). My code looks like this:
SELECT DISTINCT
devices_LOG.device_id, MAX(devices_LOG.LogDate) AS LogDate,
manufacturers.name, devices_LOG.LogType, devices_LOG.userName,
devices_LOG.userFullname, devices.invnumber, devices.modelname,
devices.modelnumber
FROM devices_LOG
INNER JOIN
devices ON devices_LOG.device_id = devices.id AND
devices_LOG.device_id = devices.id
INNER JOIN
manufacturers ON devices.manufacturer_id = manufacturers.id
WHERE (devices.devicestatus = '1') AND (devices_LOG.LogType = 'Out')
GROUP BY devices_LOG.device_id, manufacturers.name, devices_LOG.LogType,
devices_LOG.userName, devices_LOG.userFullname, devices.invnumber,
devices.modelname, devices.modelnumber
ORDER BY devices_LOG.device_id
which is great for returning only entries for things that have device.status = ‘1’, but it returns multiple log entries for something with the same device.id. So, the results of my query look like this
device_id LogDate username LogType modelname ...etc
1 11/12/2011 foo out generic
1 11/10/2011 world out generic
2 9/10/2011 hello out generic3
2 8/9/2011 bye out generic3
when I need it to look like this:
device_id LogDate username LogType modelname ...etc
1 11/12/2011 foo out generic
2 9/10/2011 hello out generic3
I tried using MAX on LogDate, tried grouping, select distinct, etc….but I just can`t figure it out. Any ideas?
I realize my sql statement is pretty ugly right now, probably because I have been trying everything I can think of up to this point with no luck, so any help would be greatly appreciated, thanks
Just wrap the log entry in a CTE and use ROW_NUMBER with partition to get the data you want.
For example if you wanted the oldest log entry, you could change the ORDER BY LogDate DESC into ASC.