简体   繁体   中英

SQL Non unique entries

I am trying to write a query that returns me the DateCode and ContainerName from two joined tables but only give me the records where DateCode is not unique (has multiple entries) I feel like the SQL query I've written should do exactly that but I keep getting this error:

Each GROUP BY expression must contain at least one column that is not an outer reference.

Perhaps I'm just too green to understand why this isn't working but here is my query:

SELECT LA.DateCode, C.ContainerName 
FROM CamstarSch.A_LotAttributes LA INNER JOIN 
     CamstarSch.Container C 
     ON C.ContainerId = LA.ContainerId
WHERE LA.DateCode IN (SELECT LA.DateCode 
                      FROM CamstarSch.A_LotAttributes 
                      GROUP BY LA.DateCode, C.ContainerName 
                      HAVING COUNT(*) > 1
                    );

Problem with subquery , DateCode should be from subquery query :

WHERE LA.DateCode IN (SELECT AL.DateCode 
                      FROM CamstarSch.A_LotAttributes AS AL
                      GROUP BY AL.DateCode 
                      HAVING COUNT(*) > 1
                    );

However, simple aggregation would also work :

SELECT LA.DateCode, C.ContainerName 
FROM CamstarSch.A_LotAttributes LA INNER JOIN 
     CamstarSch.Container C 
     ON C.ContainerId = LA.ContainerId
GROUP BY LA.DateCode, C.ContainerName 
HAVING COUNT(*) > 1;

This is a pretty easy one, you were so close!

SELECT LA.DateCode, C.ContainerName, COUNT(*)
FROM CamstarSch.A_LotAttributes LA
INNER JOIN CamstarSch.Container C ON C.ContainerId = LA.ContainerId
GROUP BY LA.DateCode, C.ContainerName 
HAVING COUNT(*)>1

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