SQL Group By子句(无效列)?

时间:2012-05-18 10:51:01

标签: sql sql-server-2005

我正在构建一些基本的SQL查询,并且已经在“group By”子句中取消了。我在列标题上使用了别名,但在尝试“分组”我的结果时遇到了问题。我的代码目前是: -

SELECT                 
  vwREP_GP_ContractProjectPurchaseCostCatID.PACOSTCATID AS COST_CAT_CODE, 
  vwREP_GP_ContractProjectPurchaseCostCatID.PACOSTCATNME AS COST_CAT_NAME, 
  vwREP_GP_ContractProjectPurchaseRpt.COST, 
  vwREP_GP_ContractProjectPurchaseRpt.ITEMDESC AS ITEM, 
  vwREP_GP_ContractProjectPurchaseRpt.CREDITOR, 
  vwREP_GP_ContractProjectPurchaseRpt.DOC_NUM AS DOCUMENT_NUMBER, 
  vwREP_GP_ContractProjectPurchaseRpt.DESCRIPTION, 
  vwREP_GP_ContractProjectPurchaseRpt.DOC_DATE AS DATE,  
  vwREP_GP_ContractProjectPurchaseRpt.PROJECT AS JOB_CODE_STAGE, 
  vwREP_GP_ContractProjectPurchaseRpt.COMPOUNDNAME AS CATEGORY_DESCRIPTION
FROM         
  vwREP_GP_ContractProjectPurchaseCostCatID 
INNER JOIN
  vwREP_GP_ContractProjectPurchaseRpt ON  wREP_GP_ContractProjectPurchaseCostCatID.PACOSTCATID = vwREP_GP_ContractProjectPurchaseRpt.PACOSTCATID


SELECT CATEGORY_DESCRIPTION, SUM(COST) AS TotalCost FROM 
    ( 
        SELECT COMPOUNDNAME AS CATEGORY_DESCRIPTION FROM wREP_GP_ContractProjectPurchaseRpt
    ) A 
GROUP BY CATEGORY_DESCRIPTION

添加了额外的代码来处理使用别名列名称我现在收到“COST”是无效列的错误?我没有改变这个列名?

我知道它显而易见地盯着我,但是我的大脑没有吸引力,所以如果有人能指出我出错的地方或者这样做的简单方法会有很大的帮助。

提前致谢。

(这是在sql server management studio 2005上完成的)

2 个答案:

答案 0 :(得分:1)

使用

SELECT COMPOUNDNAME AS CATEGORY_DESCRIPTION, 
       Sum(COST) AS TotalCost 
FROM   vwREP_GP_ContractProjectPurchaseRpt 
GROUP  BY COMPOUNDNAME 

而不是

SELECT  CATEGORY_DESCRIPTION,SUM(COST)AS TotalCost FROM 
( 
    SELECT COMPOUNDNAME AS CATEGORY_DESCRIPTION FROM vwREP_GP_ContractProjectPurchaseRpt
) A 
GROUP BY CATEGORY_DESCRIPTION

您未在内部查询中包含COST列。

答案 1 :(得分:1)

SELECT  CATEGORY_DESCRIPTION, SUM(COST) AS TotalCost
FROM    ( 
        SELECT COMPOUNDNAME AS CATEGORY_DESCRIPTION, COST
        FROM   vwREP_GP_ContractProjectPurchaseRpt
        ) A 
GROUP BY
        CATEGORY_DESCRIPTION