简体   繁体   中英

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:

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). 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:

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:

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 Fiddle Demo

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.

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
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM