使用GROUP BY和HAVING从一个表到另一个表进行选择

时间:2018-07-11 12:43:01

标签: sql-server

我正在尝试使用GROUP BYHAVING将数据从一个临时表插入另一个临时表,但是出现以下错误:

Each GROUP BY expression must contain at least one column that is not an outer reference.

这是相关的代码行:

SELECT '1200.005.032' AS GlCode, upd.Job AS Reference, Sum(upd.DiffValue) AS [Value], 
    'New Overhead Rate Change by $' + upd.RateDifference + ' Job: ' + upd.Job AS Comment, upd.PostYear, upd.PostMonth, 'POSITIVE' as TranType
INTO #LabGenJournal
FROM #UpdLaborDetails upd
GROUP BY '1200.005.032', upd.Job, 'New Overhead Rate Change by $' + upd.RateDifference + 'Job: ' + upd.Job, upd.PostYear, upd.PostMonth
HAVING (((Sum(upd.DiffValue))<>0));

2 个答案:

答案 0 :(得分:3)

您正在按常数值(“ 1200.005.032”分组,该值不是源表中的值,因此是纯“外部参考”)。尝试以下方法:

SELECT
    '1200.005.032' AS GlCode,
    upd.Job AS Reference,
    Sum(upd.DiffValue) AS [Value], 
    'New Overhead Rate Change by $' + upd.RateDifference + ' Job: ' + upd.Job AS Comment,
    upd.PostYear,
    upd.PostMonth,
    'POSITIVE' as TranType
INTO #LabGenJournal
FROM #UpdLaborDetails upd
GROUP BY upd.Job, upd.RateDifference, upd.PostYear, upd.PostMonth
HAVING (Sum(upd.DiffValue)<>0);

答案 1 :(得分:2)

一种简单易读的方法是使用sub-select

SELECT t.GlCode, t.Reference, t.Comment, t.PostYear, t.PostMonth, SUM(t.[Value]) DiffValue
INTO #LabGenJournal
FROM 
    (
        SELECT '1200.005.032' AS GlCode, upd.Job AS Reference, upd.DiffValue AS [Value], 'New Overhead Rate Change by $' + upd.RateDifference + ' Job: ' + upd.Job AS Comment, upd.PostYear, upd.PostMonth, 'POSITIVE' as TranType
        FROM #UpdLaborDetails upd
    ) t
GROUP BY t.GlCode, t.Reference, t.Comment, t.PostYear, t.PostMonth
HAVING SUM([Value]) <> 0

另一个使用common table expression

WITH cte as 
(
    SELECT '1200.005.032' AS GlCode, upd.Job AS Reference, upd.DiffValue AS [Value], 'New Overhead Rate Change by $' + upd.RateDifference + ' Job: ' + upd.Job AS Comment, upd.PostYear, upd.PostMonth, 'POSITIVE' as TranType
    FROM #UpdLaborDetails upd
)
SELECT t.GlCode, t.Reference, t.Comment, t.PostYear, t.PostMonth, SUM(t.[Value]) DiffValue
INTO #LabGenJournal
FROM cte t
GROUP BY t.GlCode, t.Reference, t.Comment, t.PostYear, t.PostMonth
HAVING SUM([Value]) <> 0