Search code examples
sqlsql-servergroup-byhaving

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
                    );

Solution

  • 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;