为什么需要分组?

时间:2017-01-12 07:42:52

标签: sql sql-server aggregate

我不是开发人员,但在开发人员帮助之前需要完成这项工作...... 我有以下几点;这是有效的,但我需要一个WHERE进入选择,使其正确,它告诉我,我需要添加到组。当我这样做时,它会“重复”结果。

什么有效:

Select  ALTEXTCUSTREF
    ,(SELECT AVG(C.SALESPRICE*C.QTY)) AS Budget
    ,select SUM(B.LEDGERSALESAMOUNT) as Labour 
from SMMACTIVITIES AS A
LEFT JOIN PROJEMPLTRANS AS B ON A.ACTIVITYNUMBER=B.ACTIVITYNUMBER
LEFT JOIN PROJFORECASTEMPL AS C ON A.ACTIVITYNUMBER=C.ACTIVITYNUMBER
WHERE A.ACTIVITYNUMBER LIKE '1234%'
group by A.ALTEXTCUSTREF, C.ACTIVITYNUMBER

但我需要在B.LEDGERSALESAMOUNT上加上条件,所以我做了以下事情;

Select  ALTEXTCUSTREF
    ,(SELECT AVG(C.SALESPRICE*C.QTY)) AS Budget
    ,(select SUM(B.LEDGERSALESAMOUNT) where B.CATEGORYID NOT LIKE 'P_%')  as Labour 
from SMMACTIVITIES AS A
LEFT JOIN PROJEMPLTRANS AS B ON A.ACTIVITYNUMBER=B.ACTIVITYNUMBER
LEFT JOIN PROJFORECASTEMPL AS C ON A.ACTIVITYNUMBER=C.ACTIVITYNUMBER
WHERE A.ACTIVITYNUMBER LIKE '1234%'
group by A.ALTEXTCUSTREF, C.ACTIVITYNUMBER

我收到了这个错误:

  

Msg 8120,Level 16,State 1,Line 4 Column'PROJEMPLTRANS.CATEGORYID'   在选择列表中无效,因为它不包含在任何一个中   聚合函数或GROUP BY子句。

但如果我将B.CATEGORYID放入群组中,我会将ALTEXTCUSTREF的行分开,这是不正确的。

请帮忙。我被困住了,没时间了。

1 个答案:

答案 0 :(得分:0)

编辑为OP的新意图

    SELECT bg.altextcustref
    ,bg.activitynumber
    ,bg.budget
    ,lb.labour
FROM
(
    SELECT altextcustref
        ,activitynumber
        ,AVG(c.salesprice * c.qty) AS budget
    FROM smmactivities AS a
    LEFT JOIN projforecastempl AS c 
    ON a.activitynumber = c.activitynumber
    WHERE a.activitynumber LIKE '1234%'
    GROUP BY a.altextcustref, c.activitynumber
) AS bg
INNER JOIN
(
    SELECT altextcustref
        ,activitynumber
        ,SUM(b.ledgersalesamount) AS labour
    FROM smmactivities AS a
    LEFT JOIN projempltrans AS b 
    ON a.activitynumber = b.activitynumber
    WHERE a.activitynumber LIKE '1234%'
        AND b.categoryid NOT LIKE 'P_%'
    GROUP BY a.altextcustref, c.activitynumber
) AS lb
ON bg.altextcustref = lb.altextcustref 
    AND bg.activitynumber = lb.activitynumber;