Skip to content
Advertisement

Need a Query to fetch distinct data from a table in my sql

I have a table History which contains below columns:

ID   Previous  Current  User     createdOn
1    RED       BLUE     System   2020-04-14 09:24:49.765000
2    GREEN     YELLOW   ADMIN    2020-04-12 03:56:34.765000
3    GREEN     BLUE     System   2020-04-14 11:37:21.765000
4    ORANGE    RED      System   2020-04-15 11:24:49.765000

I need a query to fetch data from a table in a manner that every user should return only one row for the day even if a user has more than one entry for a day

The required resultset should be as below :

User       CreatedOn
ADMIN      2020-04-12 03:56:34.765000
System     2020-04-14 09:24:49.765000
System     2020-04-15 11:24:49.765000

Advertisement

Answer

You can group by User and date and get the minimum createdOn for each user:

select User, min(createdOn) createdOn
from History
group by User, date(createdOn)

See the demo.
Results:

| User   | createdOn                  |
| ------ | -------------------------- |
| ADMIN  | 2020-04-12 03:56:34.765000 |
| System | 2020-04-14 09:24:49.765000 |
| System | 2020-04-15 11:24:49.765000 |
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement