In a problem statement I need to show last update column value on the base of DateTime column value by using Group By Statement:
Below is my SQL Server table:
Figure 1
Record in my Table:
Figure 2
Problem: I want to fetch record, such as grouping by Technology & Trainer Name but I want last updated City, Attendees &EventDate.
Yes I can use MAX(ColumnName). MAX will return correct value for EventDate but for City & Attendees it will not return.
So if I use Group By Statement:
- SELECT TRAINERNAME, TECHNOLOGY,MAX(CITY)AS CITY,MAX(ATTENDEES)AS STUDENT,
- MAX(EVENTDATE)ASDATE
- FROM EVENT_INFORMATION GROUPBY TRAINERNAME, TECHNOLOGY
Figure 3
Problem is here:
- SELECT*FROM EVENT_INFORMATION
-
- SELECT TRAINERNAME, TECHNOLOGY,MAX(CITY)AS CITY,MAX(ATTENDEES)AS STUDENT,
- MAX(EVENTDATE)ASDATE
- FROM EVENT_INFORMATION GROUPBY TRAINERNAME, TECHNOLOGY
Figure 4
So to get required result use below SQL Statement: - SELECT T.TRAINERNAME,T.TECHNOLOGY,T.CITY, T.ATTENDEES, R.MAXDATE
- FROM (
- SELECT TRAINERNAME, TECHNOLOGY,MAX(EVENTDATE)AS MAXDATE
- FROM EVENT_INFORMATION GROUPBY TRAINERNAME, TECHNOLOGY
- ) R
- INNERJOIN EVENT_INFORMATION T
- ON T.TRAINERNAME = R.TRAINERNAME AND T.TECHNOLOGY=R.TECHNOLOGY
- AND T.EVENTDATE = R.MAXDATE
Figure 5 You can compare both SQL Query result below: - SELECT TRAINERNAME, TECHNOLOGY,MAX(CITY)AS CITY,MAX(ATTENDEES)AS STUDENT,MAX(EVENTDATE)ASDATE
- FROM EVENT_INFORMATION GROUPBY TRAINERNAME, TECHNOLOGY
-
-
- SELECT T.TRAINERNAME,T.TECHNOLOGY,T.CITY, T.ATTENDEES, R.MAXDATE
- FROM (SELECT TRAINERNAME, TECHNOLOGY,MAX(EVENTDATE)AS MAXDATE
- FROM EVENT_INFORMATION GROUPBY TRAINERNAME, TECHNOLOGY
- ) R
- INNERJOIN EVENT_INFORMATION T
- ON T.TRAINERNAME = R.TRAINERNAME AND T.TECHNOLOGY=R.TECHNOLOGY
- AND T.EVENTDATE = R.MAXDATE
Figure 6