如何按SQL Server中的部分列进行分组

时间:2017-08-02 15:37:12

标签: sql sql-server sql-server-2008

我选择了一些列,DATE列是datetime,我想只按收据标题ID和收据详细信息项类别分组,但是我运行SQL,我收到错误。如何成功运行?

select 
    DATE as DATE, 
    RECEIPT_ID,
    CATEGORY1, CATEGORY2,
    SUM(CEILING(TOTAL_QTY / MEASURE.CONVERSION_QTY)) AS Qty,
    SUM(ROUND(CEILING(TOTAL_QTY / MEASURE.CONVERSION_QTY) * 
        ROUND(MEASURE.LENGTH * MEASURE.WIDTH * MEASURE.HEIGHT/ 1000000.0, 9), 2)) AS cbm
from 
    RECEIPT 
left join 
    MEASURE ON MEASURE.item = RECEIPT.ITEM 
            AND MEASURE.company = RECEIPT.COMPANY
where
    MEASURE.QUANTITY_UM = 'ctn'
group by 
    RECEIPT_ID, CATEGORY1

5 个答案:

答案 0 :(得分:1)

必须按所有非聚合列进行分组,这些列是您的select子句的一部分。我已修改您的查询以执行此操作 - 请参阅下文 如果您只需要RECEIPT_ID和category1 GROUP BY,那么您就不需要显示其他两列(日期和类别2),因为它们已合并。

   SELECT 
      DATE as DATE, 
      RECEIPT_ID,
      CATEGORY1, 
      CATEGORY2,
      SUM(CEILING( TOTAL_QTY /MEASURE.CONVERSION_QTY )) as Qty,
      SUM(Round( CEILING( TOTAL_QTY /MEASURE.CONVERSION_QTY )* Round( MEASURE.LENGTH * MEASURE.WIDTH * MEASURE.HEIGHT/ 1000000.0, 9 ), 2 )) as cbm
   from RECEIPT 
   left join MEASURE on MEASURE.item = RECEIPT.ITEM AND MEASURE.company = RECEIPT.COMPANY
   WHERE MEASURE.QUANTITY_UM = 'ctn'
  GROUP BY Date, RECEIPT_ID, CATEGORY1, CATEGORY2

答案 1 :(得分:0)

如果您没有对DATECategory2进行分组,请从查询中删除它们:

 select RECEIPT_ID,
   CATEGORY1, 
   SUM(CEILING( TOTAL_QTY /MEASURE.CONVERSION_QTY )) as Qty,
   SUM(Round( CEILING( TOTAL_QTY /MEASURE.CONVERSION_QTY )* Round( MEASURE.LENGTH * MEASURE.WIDTH * MEASURE.HEIGHT/ 1000000.0, 9 ), 2 )) as cbm
   from RECEIPT 
   left join MEASURE on MEASURE.item = RECEIPT.ITEM AND MEASURE.company = RECEIPT.COMPANY
   WHERE MEASURE.QUANTITY_UM = 'ctn'
   group by RECEIPT_ID, CATEGORY1

使用GROUP BY时,SQL要求SELECT子句中的所有字段都是:

  1. 列在您的GROUP BY条款或
  2. 包含内部聚合函数(例如MINSUM等)

答案 2 :(得分:0)

我怀疑你得到的错误是:

 Column 'XXXXX' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

您必须对您选择的其他列进行GROUP BY(除了总和)或进行一些复合查询以获取所需的数据

      group by DATE, RECEIPT_ID, CATEGORY1, CATEGORY2

答案 3 :(得分:0)

每当你在查询中尝试使用GROUP BY时,你必须提到除了AGGREGATE函数之外的所有其他列.Coz,GROUP BY基于选择中的其他列发生。你不能拥有Select CLAUSE中的所有列。

根据您发布的要求说明,即您需要按RECEIPT_ID和CATEGORY1和CATEGORY2分组,您的查询应如下所示

select 
   RECEIPT_ID,
   CATEGORY1, 
   CATEGORY2,
   SUM(CEILING( TOTAL_QTY /MEASURE.CONVERSION_QTY )) as Qty,
   SUM(Round( CEILING( TOTAL_QTY /MEASURE.CONVERSION_QTY )* Round( MEASURE.LENGTH * MEASURE.WIDTH * MEASURE.HEIGHT/ 1000000.0, 9 ), 2 )) as cbm
   from RECEIPT 
   left join MEASURE on MEASURE.item = RECEIPT.ITEM AND MEASURE.company = RECEIPT.COMPANY
   WHERE MEASURE.QUANTITY_UM = 'ctn'
   group by RECEIPT_ID, CATEGORY1,CATEGORY2

答案 4 :(得分:0)

如果SQL中有聚合函数,则所有非聚合列都必须出现在group by子句中。作为解决方法,您可以使用例如union,因此在第一个SQL子句中可以使用

SELECT RECEIPT_ID, CATEGORY1和SUM,在第二个查询中,您将获得其余列