Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Condition on duplicate rows

I have 4 columns:

user id, start date (D/M/Y), type and name

user_id | start_date | type | name
1       | 1-01-2017  | 0    | Jack
1       | 1-01-2017  | 1    | Jack
1       | 2-01-2017  | 0    | Jack 
1       | 3-01-2017  | 0    | Jack
1       | 4-01-2017  | 0    | Jack 
1       | 5-01-2017  | 0    | Jack

I want to retrieve data by id ,type and start date .But the condition is, I want only single record, if date is same and priority is where type = 1 . Don't want duplicate dates. I already tried Group by but it shows only where type is 0.

I want Like this :

user_id | start_date | type | name
1       | 1-01-2017  | 1    | Jack
1       | 2-01-2017  | 0    | Jack 
1       | 3-01-2017  | 0    | Jack
1       | 4-01-2017  | 0    | Jack 
1       | 5-01-2017  | 0    | Jack

GROUP BY Result :

user_id | start_date | type | name
1       | 1-01-2017  | 0    | Jack
1       | 2-01-2017  | 0    | Jack 
1       | 3-01-2017  | 0    | Jack
1       | 4-01-2017  | 0    | Jack 
1       | 5-01-2017  | 0    | Jack
like image 722
Taha Farooqui Avatar asked Nov 27 '25 05:11

Taha Farooqui


1 Answers

I don't understand what exactly are you looking for, but the following query, will give you the exact results you are looking for:

SELECT MAX(user_id) AS user_id, 
  start_date,
  MAX(type) AS type, 
  MAX(name) as name
FROM data AS d1  
GROUP BY start_date;

Results:

| user_id |           start_date | type | name |
|---------|----------------------|------|------|
|       1 | 2017-01-01T00:00:00Z |    1 | Jack |
|       1 | 2017-02-01T00:00:00Z |    0 | Jack |
|       1 | 2017-03-01T00:00:00Z |    0 | Jack |
|       1 | 2017-04-01T00:00:00Z |    0 | Jack |
|       1 | 2017-05-01T00:00:00Z |    0 | Jack |

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!