I would use RANK()
function for this.
SELECT * FROM
(
SELECT DISTINCT Standortname,
DATEPART(YEAR,PK_Date) AS Jahr,
DATEPART(month,PK_Date) AS Monat,
Lizenzname,
COUNT(DISTINCT username) AS AnzahlUser,
SUM(DISTINCT DATEDIFF(minute,starttime ,pk_date)) AS RuntimeMinute,
endtime,
pk_date,
RANK() Over (PARTITION BY username ORDER BY pk_date DESC) As Rank
FROM BenutzerLizenz,Benutzer,Abteilung,Lizenz,Standort
WHERE
BenutzerLizenz.PK_ID_user=Benutzer.PK_ID_user
AND BenutzerLizenz.PK_ID_lic=Lizenz.PK_ID_lic
AND PK_ID_standort=FK_ID_standort
AND DATEPART(month,PK_Date) = '04'
AND DATEPART(YEAR,PK_Date) = '2013'
AND Lizenzname = 'iman_1st'
AND Standortname = 'Unterlüß'
GROUP BY
Standortname,
DATEPART(YEAR,PK_Date),
DATEPART(month,PK_Date),
Lizenzname,
starttime,
endtime,
pk_date,
username
) tmp where Rank=1
The RANK()
functions ranks each row of a result set in the order defined by ORDER BY
. Used with PARTITION BY
, you can further partition the data for ranking.
Since you already have the data that you need, you will partition the result by username
and rank the pk_date
in order to get the highest one.