左连接后无法分组

时间:2009-12-23 07:41:25

标签: sql-server tsql triggers group-by grouping

这是我的查询(来自触发器):

UPDATE QuoteItemsGroupFeature
SET Cost = (QuoteItemsGroup.BaseCost + QuoteItemsGroup.AccumulatedCost + 
    ISNULL(SUM(ParentQuoteItemsGroupFeature.Cost), 0)) * INSERTED.Amount
FROM QuoteItemsGroupFeature INNER JOIN INSERTED
    ON QuoteItemsGroupFeature.QuoteItemsGroupFeatureId = 
    INSERTED.QuoteItemsGroupFeatureId
INNER JOIN QuoteItemsGroup ON QuoteItemsGroup.QuoteItemsGroupId = 
    INSERTED.QuoteItemsGroupId
LEFT OUTER JOIN QuoteItemsGroupFeature ParentQuoteItemsGroupFeature ON 
    ParentQuoteItemsGroupFeature.QuoteItemsGroupFeatureId = 
    INSERTED.ParentQuoteItemsGroupFeatureId
GROUP BY QuoteItemsGroup.BaseCost, 
    QuoteItemsGroup.AccumulatedCost, 
    INSERTED.Feature, 
    INSERTED.Cost

它说:

Msg 156, Level 15, State 1, Line 7
Incorrect syntax near the keyword 'GROUP'.

1 个答案:

答案 0 :(得分:6)

您必须将聚合删除到派生表(或CTE)

我认为这就是你想要的,我认为你的团队也是错的。我还添加了别名以便于阅读(对我来说无论如何)

UPDATE
    QF
SET
    Cost = foo.Cost
FROM
    QuoteItemsGroupFeature QF JOIN 
    (
    SELECT
        I.QuoteItemsGroupFeatureId,
        (Q.BaseCost + Q.AccumulatedCost + ISNULL(SUM(P.Cost), 0)) * I.Amount 
            AS Cost
    FROM
        INSERTED I
        JOIN
        QuoteItemsGroup Q ON Q.QuoteItemsGroupId = I.QuoteItemsGroupId
        LEFT JOIN
        QuoteItemsGroupFeature P ON 
            P.QuoteItemsGroupFeatureId = I.ParentQuoteItemsGroupFeatureId
    GROUP BY
        Q.BaseCost, 
        Q.AccumulatedCost, 
        --I.Feature, ??
        --I.Cost, ??
        I.Amount
    ) foo ON QF.QuoteItemsGroupFeatureId = foo.QuoteItemsGroupFeatureId