Search code examples
sqlms-accessgroup-bygrouping

Access SQL GROUP BY problem (eg. tbl_Produktion.ID not part of the aggregation-function)


I want to group by two columns, however MS Access won't let me do it.

Here is the code I wrote:

SELECT 
    tbl_Produktion.Datum, tbl_Produktion.Schichtleiter,     
    tbl_Produktion.ProduktionsID, tbl_Produktion.Linie,  
    tbl_Produktion.Schicht, tbl_Produktion.Anzahl_Schichten_P, 
    tbl_Produktion.Schichtteam, tbl_Produktion.Von, tbl_Produktion.Bis, 
    tbl_Produktion.Pause, tbl_Produktion.Kunde, tbl_Produktion.TeileNr, 
    tbl_Produktion.FormNr, tbl_Produktion.LabyNr, 
    SUM(tbl_Produktion.Stueckzahl_Prod), 
    tbl_Produktion.Stueckzahl_Ausschuss, tbl_Produktion.Ausschussgrund, 
    tbl_Produktion.Kommentar, tbl_Produktion.StvSchichtleiter,   
    tbl_Produktion.Von2, tbl_Produktion.Bis2, tbl_Produktion.Pause2, 
    tbl_Produktion.Arbeiter3, tbl_Produktion.Von3, tbl_Produktion.Bis3,   
    tbl_Produktion.Pause3, tbl_Produktion.Arbeiter4, 
    tbl_Produktion.Von4, tbl_Produktion.Bis4, tbl_Produktion.Pause4, 
    tbl_Produktion.Leiharbeiter5, tbl_Produktion.Von5, 
    tbl_Produktion.Bis5, tbl_Produktion.Pause5, 
    tbl_Produktion.Leiharbeiter6, tbl_Produktion.Von6, 
    tbl_Produktion.Bis6, tbl_Produktion.Pause6, tbl_Produktion.Muster
FROM 
    tbl_Personal 
INNER JOIN 
    tbl_Produktion ON tbl_Personal.PersID = tbl_Produktion.Schichtleiter
GROUP BY  
    tbl_Produktion.Datum, tbl_Produktion.Schichtleiter;

It works when I group it by all the columns, but not like this.

The error message say that the rest of the columns aren't part of the aggregation-function (translated from german to english as best as I could).

PS.: I also need the sum of "tbl_Produktion.Stueckzahl_Prod" therefore I tried using the SUM function (couldn't try it yet).


Solution

  • Have you tried something along these lines?

    SELECT 
        tbl_Produktion.Datum, tbl_Produktion.Schichtleiter,     
        MAX(tbl_Produktion.ProduktionsID), MAX(tbl_Produktion.Linie),  
        MAX(tbl_Produktion.Schicht), MAX(tbl_Produktion.Anzahl_Schichten_P), 
        MAX(tbl_Produktion.Schichtteam), MAX(tbl_Produktion.Von), MAX(tbl_Produktion.Bis), 
        SUM(tbl_Produktion.Stueckzahl_Prod)
    FROM
        tbl_Personal 
    INNER JOIN 
        tbl_Produktion ON tbl_Personal.PersID = tbl_Produktion.Schichtleiter
    GROUP BY  
        tbl_Produktion.Datum, tbl_Produktion.Schichtleiter;
    

    I have used the MAX function for all the data except the two items you specify in the GROUP BY and the one where you desire the SUM. I took the liberty of leaving out mush of your data just to get started.

    Using the MAX function turns out to be a convenient workaround when the data item is known to be unique within each group. We cannot know your data or your itent, so we cannot tell you whether MAX will yield the results you need.