I have a table with the following structure (dummy column names and data):
+--+--+--+--+------+--------+
|a |b |c |d |issue |content |
+--+--+--+--+------+--------+
|a |b |c |d |1 | |
|a |b |c |d |2 | |
|a |b |c |d |3 | |
|d |e |f |g |1 | |
|d |e |f |g |2 | |
|e |f |g |h |1 | |
+--+--+--+--+------+--------+
My primary key contains columns a, b, c, d and issue.
I need a statement that first filters / groups by columns a, b, c and d and then only selects the record with MAX(issue). For this example the result set should look like this:
+--+--+--+--+------+--------+
|a |b |c |d |issue |content |
+--+--+--+--+------+--------+
|a |b |c |d |3 | |
|d |e |f |g |2 | |
|e |f |g |h |1 | |
+--+--+--+--+------+--------+
I know how I would do this for one specific record, but I cannot figure out how to do it for all the records:
SELECT TOP 1 * FROM Test_Max_N_Per_Group
WHERE a = 'a' AND b = 'b' AND c = 'c' AND d = 'd'
ORDER BY issue DESC
I am using Microsoft SQL Server 2008 R2.
// Edit: Thank you guys, I found this (very compact) solution in another topic:
SELECT t1.* FROM Test_Max_N_Per_Group t1
LEFT JOIN Test_Max_N_Per_Group t2
ON t1.a = t2.a AND t1.b = t2.b AND t1.c = t2.c AND t1.d = t2.d AND
t1.issue < t2.issue
WHERE t2.issue IS NULL