GROUP BY出错

时间:2017-08-16 15:43:08

标签: sql-server

enter image description here

以上是我的数据,当我运行SQL时,我收到了一个错误。请帮忙

  

每个GROUP BY表达式必须至少包含一个不是外部引用的列。

查询:

SELECT          
    LEFT(RTRIM(LEFT(IBDA.CUST_PO_I, 11)) + 
        LEFT(IBDA.CUST_PO_LINE_I, 3) + SPACE(14), 14) AS 'UNIQUE ID', 
    LEFT('' + Space(15), 15) AS 'PACK SLIP', 
    LEFT(CONVERT(VARCHAR(10), IBDA.CALENDAR_INVC_D, 101) + Space(15), 15) AS 'DATE', 
    LEFT('vend' + Space(9), 9) AS 'VEND', 
    LEFT(Ltrim(Rtrim(IBDA.SHIP_Q)) + Space(12), 12) AS 'QUANTITY', 
    U.BASE_UOM AS 'UNIT OF MEASURE' 
FROM   
    AXE4321.AA.DBO.1TB IBDA 
LEFT JOIN 
    AXE1234.BB.DBO.2TB U ON IBDA.UOM_C = U.UOM_C 
WHERE  
    IBDA.CUST_I = '9377467' 
GROUP BY 
    'UNIQUE ID'
ORDER BY 
    [UNIQUE ID] DESC 

1 个答案:

答案 0 :(得分:1)

我个人会使用CTE:

WITH CTE1
AS
(SELECT          
LEFT(RTRIM(LEFT(IBDA.CUST_PO_I, 11)) + 
    LEFT(IBDA.CUST_PO_LINE_I, 3) + SPACE(14), 14) AS 'UNIQUE ID', 
LEFT('' + Space(15), 15) AS 'PACK SLIP', 
LEFT(CONVERT(VARCHAR(10), IBDA.CALENDAR_INVC_D, 101) + Space(15), 15) AS 'DATE', 
LEFT('vend' + Space(9), 9) AS 'VEND', 
LEFT(Ltrim(Rtrim(IBDA.SHIP_Q)) + Space(12), 12) AS 'QUANTITY', 
U.BASE_UOM AS 'UNIT OF MEASURE' 
FROM   
AXE4321.AA.DBO.1TB IBDA 
LEFT JOIN 
AXE1234.BB.DBO.2TB U ON IBDA.UOM_C = U.UOM_C 
WHERE  
IBDA.CUST_I = '9377467' 
ORDER BY 
[UNIQUE ID] DESC)

SELECT [UNIQUE ID], MAX([PACK SLIP]), DATE, VEND, SUM(QUANTITY), [UNIT OF MEASURE] --PACK SLIP seems like it's an empty column, so you could probably leave it out?
FROM CTE1
GROUP BY [UNIQUE ID], DATE, [UNIT OF MEASURE], VEND

我认为这应该做你需要的,但这仍然需要修改。请仅将此作为参考,并相应地调整聚合。