HaniBey
HaniBey

Reputation: 13

SQL Query Group By Help

I have the following data:

cust  subject  date
Cust1 Subject1 2010-12-31 21:59:59.000
Cust1 Subject1 2010-12-31 21:59:59.000
Cust4 Subject3 2011-02-27 21:59:59.000
Cust5 Subject1 2010-10-31 21:59:59.000
Cust5 Subject2 2010-10-31 21:59:59.000
Cust6 Subject2 2010-10-31 21:59:59.000
Cust6 Subject2 2010-12-31 21:59:59.000

I need to achieve the following:

The result of the query should be:

cust  subject  date
Cust1 Subject1 2010-12-31 21:59:59.000
Cust4 Subject3 2011-02-27 21:59:59.000
Cust5 Subject1 2010-10-31 21:59:59.000
Cust5 Subject2 2010-10-31 21:59:59.000
Cust6 Subject2 2010-12-31 21:59:59.000

Can anyone help me with this?

I managed to do 2 of the requirements but not all 3.

Upvotes: 1

Views: 75

Answers (3)

Will A
Will A

Reputation: 24988

Use ROW_NUMBER() - if you've not used this and the other partitioning functions previously then I can definitely recommend looking into them as they (especially ROW_NUMBER()) have a great deal of uses.

SELECT cust, subject, date
FROM (
  SELECT cust, subject, date, ROW_NUMBER() OVER (PARTITION BY cust, subject ORDER BY date DESC) AS RN
  FROM <your table>
) SubQuery
WHERE SubQuery.RN = 1

Upvotes: 0

xagyg
xagyg

Reputation: 9711

select cust, subject, max(date) from table group by cust, subject

Upvotes: 0

Asaph
Asaph

Reputation: 162771

SELECT cust, subject, max([date]) FROM myTable GROUP BY cust, subject;

You don't really have a column called date, do you? date is a reserved word which is why it had to be surrounded by square braces in my query above.

Upvotes: 5

Related Questions