3

I m using the following query, to get the result as shown below. Actually the query is just joining 2 tables.

SELECT MT.mkt_Area_ID,MA.mkt_Reg_ID,MT.mktcate_id,MT.target_Amt,MT.year 
FROM [CRM].[tblMktArea_Target] MT JOIN CRM.tblMarketingArea MA 
ON MA.mkt_Area_ID= MT.mkt_Area_ID WHERE month IN (05,04) AND year=2013 AND MA.mkt_Area_ID=1 
AND MA.mkt_Reg_ID =1 

enter image description here

How can I group the results by mktcate_id to get the sum of target_amt for each category?

I tried:

SELECT MT.mkt_Area_ID,MA.mkt_Reg_ID,MT.mktcate_id,Sum(MT.target_Amt),MT.year 
    FROM [CRM].[tblMktArea_Target] MT JOIN CRM.tblMarketingArea MA 
    ON MA.mkt_Area_ID= MT.mkt_Area_ID WHERE month IN (05,04) AND year=2013 AND MA.mkt_Area_ID=1 
    AND MA.mkt_Reg_ID =1 group by MT.mktcate_id

and getting errror

4

2 回答 2

2

GROUP BY您得到一个例外,因为有必要在子句中添加非聚合列。例子,

SELECT MT.mkt_area_id, 
       MA.mkt_reg_id, 
       MT.mktcate_id, 
       SUM(MT.target_amt), 
       MT.year 
FROM   [CRM].[TBLMKTAREA_TARGET] MT 
       JOIN CRM.TBLMARKETINGAREA MA 
         ON MA.mkt_area_id = MT.mkt_area_id 
WHERE  month IN ( 05, 04 ) 
       AND year = 2013 
       AND MA.mkt_area_id = 1 
       AND MA.mkt_reg_id = 1 
GROUP  BY   MT.mktcate_id, 
            MT.mkt_area_id, 
            MA.mkt_reg_id,
            MT.year
于 2013-05-31T06:02:42.877 回答
1

您应该始终对不在聚合函数中的所有列(例如 SUM、MAX、AVG)进行 GROUP BY。将 MT.mkt_Area_ID、MA.mkt_Reg_ID、MT.year 字段放入 GROUP BY 子句中:

 SELECT MT.mkt_Area_ID,
           MA.mkt_Reg_ID,
           MT.mktcate_id,
           Sum(MT.target_Amt),
           MT.year 
      FROM [CRM].[tblMktArea_Target] MT JOIN CRM.tblMarketingArea MA ON 
              MA.mkt_Area_ID = MT.mkt_Area_ID 
     WHERE month IN (05,04) AND 
           year = 2013 AND 
           MA.mkt_Area_ID = 1 AND 
           MA.mkt_Reg_ID = 1 
  GROUP BY MT.mktcate_id,
           MT.mkt_Area_ID,
           MA.mkt_Reg_ID,
           MT.year

或者从 SELECT 子句中删除 MT.mkt_Area_ID、MA.mkt_Reg_ID、MT.year 字段:

 SELECT MT.mktcate_id,
           Sum(MT.target_Amt)
     FROM [CRM].[tblMktArea_Target] MT JOIN CRM.tblMarketingArea MA ON 
            MA.mkt_Area_ID = MT.mkt_Area_ID 
     WHERE month IN (05,04) AND 
           year = 2013 AND 
           MA.mkt_Area_ID = 1 AND 
           MA.mkt_Reg_ID = 1 
  GROUP BY MT.mktcate_id
于 2013-05-31T06:10:30.160 回答