Mysql 在特定日期添加记录时,如何显示组中所有潜在的重复匹配项
我在为这个查询提出逻辑解决方案时遇到了问题 假设我有这个数据集Mysql 在特定日期添加记录时,如何显示组中所有潜在的重复匹配项,mysql,sql,Mysql,Sql,我在为这个查询提出逻辑解决方案时遇到了问题 假设我有这个数据集 | id | firstname | lastname | productionunit | lastmodifieddate | |----|-----------|----------|----------------|----------------------------| | 1 | John | Smith | UnitA | December, 29 2016 0
| id | firstname | lastname | productionunit | lastmodifieddate |
|----|-----------|----------|----------------|----------------------------|
| 1 | John | Smith | UnitA | December, 29 2016 00:00:00 |
| 2 | Rachel | Smith | UnitA | December, 31 2016 00:00:00 |
| 3 | Abby | Turner | UnitA | January, 04 2017 00:00:00 |
| 4 | Sam | Telly | UnitA | December, 29 2016 00:00:00 |
| 5 | Mac | Telly | UnitB | December, 30 2016 00:00:00 |
| 6 | Lincoln | Telly | UnitB | January, 01 2017 00:00:00 |
| 7 | Sam | Telly | UnitC | December, 30 2016 00:00:00 |
| 8 | Test | Smith | UnitD | December, 30 2016 00:00:00 |
只要ProductionUnit中的LastName相同,我就需要找到重复项
如果在2016年12月30日添加了一个记录,我只想要这些重复组
这是我写的问题
SELECT
a.id,
a.firstname,
a.lastname,
a.productionunit,
a.lastmodifieddate
FROM forgerock a
JOIN (SELECT
productionunit ,lastname,
COUNT(*) AS cnt
FROM forgerock
WHERE lastname in ( select lastname from forgerock
where lastmodifieddate='2016-12-30')
GROUP BY productionunit, lastname
HAVING count(*)>1 ) b
ON a.lastname = b.lastname and a.productionunit=b.productionunit
此查询提供以下结果:
| id | firstname | lastname | productionunit | lastmodifieddate |
|----|-----------|----------|----------------|----------------------------|
| 1 | John | Smith | UnitA | December, 29 2016 00:00:00 |
| 2 | Rachel | Smith | UnitA | December, 31 2016 00:00:00 |
| 5 | Mac | Telly | UnitB | December, 30 2016 00:00:00 |
| 6 | Lincoln | Telly | UnitB | January, 01 2017 00:00:00 |
这是期望的结果
| id | firstname | lastname | productionunit | lastmodifieddate |
|----|-----------|----------|----------------|----------------------------|
| 5 | Mac | Telly | UnitB | December, 30 2016 00:00:00 |
| 6 | Lincoln | Telly | UnitB | January, 01 2017 00:00:00 |
我认为问题在于where子句中的子查询。我搜索了所有最后修改日期为12-30的姓氏,而实际上我只想要productionunit中修改日期为12-30的姓氏
希望这有意义
谢谢
这里有一个schema的sqlfiddle链接:您可以将子查询更改为更简单,因为您只需查找在该日期编辑了productionunit/lastname组合的任何实例。下面的子查询可以做到这一点
SELECT DISTINCT
needle.productionunit,
needle.lastname
FROM forgerock needle
INNER JOIN forgerock haystack
ON haystack.lastname = needle.lastname
AND haystack.productionunit = needle.productionunit
AND haystack.id != needle.id
WHERE needle.lastmodifieddate = '2016-12-30'
它就在你的SQL小提琴中:你就是那个男人!非常感谢。我想知道什么时候我能在几分钟内掌握这样的SQL:)再次感谢