从两个表中选择计数和分组?

时间:2014-06-13 09:33:00

标签: sql ms-access

我有两个表格Affaire(ID, Obj, ID_TA ...)TypeAffaire(ID_TA, Label),我想计算Affaire中每个ID_TA的数量,如果label则显示ID_TA,我试过这个,但它不起作用:

SELECT  A.ID_TA
    ,T.Label
    ,count(*) AS TotalAmount
FROM    Affaire AS A
LEFT JOIN TypeAffaire AS T ON T.ID_TA = A.TA
GROUP BY A.ID_TA;

它说无法找到标签

3 个答案:

答案 0 :(得分:1)

您还需要按T.Label进行分组。 select子句中的所有非聚合字段也必须位于group by子句中。

答案 1 :(得分:1)

Group By

中添加T.Label

试试这个

SELECT  A.ID_TA
    ,T.Label
    ,count(*) AS TotalAmount
FROM    Affaire AS A
LEFT JOIN TypeAffaire AS T ON T.ID_TA = A.TA
GROUP BY A.ID_TA,T.Label;

答案 2 :(得分:0)

您需要在group by子句中插入T.Label,并更正ON T.ID_TA = A.TA in to ON T.ID_TA = A.ID_TA

SELECT  A.ID_TA ,T.Label ,count(*) AS TotalAmount
FROM  Affaire AS A
LEFT JOIN TypeAffaire AS T ON T.ID_TA = A.ID_TA
GROUP BY A.ID_TA, T.Label;