selecting duplicate values with a condition from a mysql table

时间:2015-11-12 10:47:51

标签: mysql

I have the following table in mysql:

   Key    DI     CI     FD      FA  NM  Valid_from   Valid_to
    0   1224468 123 2012-06-30  3   6   2013-01-23  9999-12-31
    1   1234567 123 2013-12-31  3   10  2014-02-27  2014-03-10
    2   1234567 123 2013-12-31  2   12  2014-03-10  9999-12-31
    3   1234579 123 2013-12-31  3   12  2014-05-15  9999-12-31
    4   1234595 123 2013-12-31  1   12  2014-06-30  9999-12-31
    5   122469  123 2015-11-11  1   6   2015-11-11  9999-12-31
    6   1224470 123 2015-11-11  2   12  2015-11-11  9999-12-31
    7   1224471 123 2015-11-11  3   15  2015-11-11  9999-12-31
    8   1224472 123 2015-11-10  2   13  2015-11-10  9999-12-31
    9   1224473 123 2015-11-10  3   12  2015-11-10  9999-12-31

If there are records which has the same "FD", I need to get the ones which 's "FA" is "1", if exists.

Basically, I want this output.

Key   DI     CI     FD      FA  NM  Valid_from   Valid_to
 0  1224468 123 2012-06-30  3   6   2013-01-23  9999-12-31
 4  1234595 123 2013-12-31  1   12  2014-06-30  9999-12-31
 5  122469  123 2015-11-11  1   6   2015-11-11  9999-12-31
 8  1224472 123 2015-11-10  2   13  2015-11-10  9999-12-31
 9  1224473 123 2015-11-10  3   12  2015-11-10  9999-12-31

It looks a complicated query, and I couldn't manage to do it.

How can I do it?

Thanks

3 个答案:

答案 0 :(得分:1)

Looks like a job for ... GROUP BY FD ... HAVING COUNT(FD) > 1

I don't see why you'd want 2012-06-30 in your results? I thought you only wanted ones where there is an FA of 1?

答案 1 :(得分:1)

Try out following query:

select * from tbl group by fd having count(*)=1
union all
select t1.* from tbl t1 inner join (
    select max(`key`) as `key` from tbl where fa=1 group by fd
) t2 on t1.`key`=t2.`key` group by FD;

答案 2 :(得分:1)

 SELECT T1.*
    FROM table_name T1 LEFT JOIN
     (SELECT * FROM table_name GROUP BY `FD` HAVING COUNT(*)>1 ) T2 ON T1.`FD`=T2.`FD` AND T1.`FA` <>1
WHERE T2.`FD` IS NULL

你能检查一下吗? 希望这会有所帮助。