I need to read users from the old database for use in statistics on the new system, but I do not have the original user table. However, there is a statistics table with the sum of each year, where I can also find all the necessary user information. In addition, it also gives me only those users who were active, and this is what I need.
The table has the following corresponding columns: (statistics columns are not relevant here)
- User ID
- Firstname
- Lastname
- Email
- Year
I want the UserID to be different, so this is the only column I can have in GROUP BY. I will run MAX on Year to get values ββfrom the very last year. FirstName, LastName, and Email must match the string MAX (Year). In other words, people could change names and emails over the years, and I only need the latter, as it is relevant.
My best suggestion for an SQL query is as follows:
SELECT UserID, Firstname, LastName, Email, MAX(Year) AS Year FROM myTable GROUP BY UserID ORDER BY LastName, FirstName
The only problem is that SQL Server 2008 will not let me do anything like that, because all columns must be with the MAX function or the GROUP BY part. The FirstName, LastName, and Email columns cannot be under GROUP BY because this will make too many entries. Something seems to work to put MAX on all of them, but then I have no way of knowing which column the MAX function works in. I donβt know for sure that this will be a problem, but I donβt have time to look at 100,000 lines to see if the problem really is.
In short, I need a whole row of five columns, where MAX works with only one column, and GROUP BY with another. Does anyone have a good solution or is it safe to use MAX for all ungrouped rows?