重复行的条件

时间:2017-12-25 20:10:21

标签: mysql sql group-by

我有4列:

用户ID,开始日期(D / M / Y),类型和名称

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

我想按id,类型和开始日期检索数据。但条件是,我只想要单个记录,如果日期相同且优先级是type = 1。不要重复日期。我已经尝试了Group by,但它只显示了type为0的位置。

我想这样:

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结果:

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

2 个答案:

答案 0 :(得分:6)

我不明白您究竟在寻找什么,但以下查询将为您提供您所寻找的确切结果:

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 |

答案 1 :(得分:4)

只需从您的数据中选择MAX(type)

SELECT user_id, start_date, MAX(type) AS x_type, name
FROM testdata
GROUP BY user_id , start_date, name

每个user_id, start_date, name元组返回一行:

| user_id | start_date | x_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 |