[英]SQL Query, GROUP/COUNT issue with INNER JOIN
I've got a data set composed primarily of dates, IDs, and addresses, that looks a bit like this: 我有一个主要由日期,ID和地址组成的数据集,看起来有点像这样:
datadate id address
20150801 Bob 123
20150801 Bob 123
20150801 Dan 345
20150801 Dan 456
20150801 Dan 567
20150801 George 234
20150801 Jim 123
20150801 Jim 123
20150801 John 678
20150801 John 123
20150802 Tom 123
20150802 Tom 234
20150802 Tom 345
My goal is to write a query which identifies any IDs which are associated with multiple distinct addresses for a specific date (or date range). 我的目标是编写一个查询,以标识与特定日期(或日期范围)的多个不同地址相关联的所有ID。 I want the query results to give me the name and distinct addresses. 我想查询结果给我名字和不同的地址。 So, for this data set, the results I'd like to see would look like this, for date 8/1/2015: 因此,对于该数据集,我希望看到的结果在2015年8月1日看起来像这样:
datadate id address
20150801 Dan 345
20150801 Dan 456
20150801 Dan 567
20150801 John 678
20150801 John 123
The query I've worked up so far is this, but it's not really working for me: 到目前为止,我已经处理过的查询是这样,但对我来说并不是真正的工作:
SELECT a.[datadate], a.[id], a.[address], b.[count1]
FROM table1 AS a INNER JOIN (SELECT [id], COUNT([address]) as [count1] FROM table1 GROUP BY [id] having count1 > 1 ) AS b ON a.[id]=b.[id]
WHERE a.[datadate] = '20150801'
ORDER BY a.[id], a.[address];
Any suggestions? 有什么建议么?
Just modifying your existing query a little bit, you can change your having to count(distinct address)
and then joining back to the table to get your address values like this: 只需稍微修改现有查询,就可以更改必须count(distinct address)
,然后重新连接到表以获取地址值,如下所示:
SELECT t.datadate
,t.id
,t1.address
FROM (
SELECT datadate
,id
,count(DISTINCT address) address
FROM test
WHERE datadate = '20150801'
GROUP BY datadate,id
HAVING count(DISTINCT address) > 1
) t
INNER JOIN test t1 ON t.datadate = t1.datadate
AND t.id = t1.id;
I tested this on SQL Server
, but should be similar in MS-Access
as well. 我在SQL Server
上进行了测试,但在MS-Access
中也应该类似。
Edit 编辑
I just read your question again and it appears you want all duplicates. 我只是再次阅读了您的问题,看来您想要所有重复项。 In which case I would use exists
to see if another row with the same id but a different address exists. 在这种情况下,我将使用exists
来查看是否exists
具有相同ID但地址不同的另一行。
select * from mytable t1
where datadate = '20150801'
and exists (
select 1 from mytable t2
where t2.id = t1.id
and t2.address <> t1.address
and t2.datadate = t1.datadate
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.