T-SQL-与分组相结合,与group by结合使用

时间:2017-07-26 08:37:54

标签: sql sql-server tsql

我正在尝试通过一个正常的sql语句来获得分区的总和但是代码不起作用。技术:SQL Server 2014

以下是代码:

select  
     ZABF$,ZUNR$,ZONR$,FPLN$,ZSTR$,right(left(GABS$,3),2) as Region

    ,SUM(Nettobetrag) AS NettoUmsatz
    ,SUM(BRUTTOBETRAG) AS BruttoUmsatz
    ,SUM(Nettobetrag) over (partition by ZABF$,ZUNR$,ZONR$,FPLN$,right(left(GABS$,3),2))

from
     ArchivZBEW.PROD.sFCTS_G195
where 
    NETTOBETRAG<>0 and right(left(GABS$,3),2)<>'65' 
    and UTYP$ in('K','M','P')
group by
    ZABF$,ZUNR$,ZONR$,FPLN$,ZSTR$,right(left(GABS$,3),2)

正如您所看到的,我尝试获得第一行中所有列的输出,然后是不同的总和。 NettoUmsatz和Bruttoumsatz工作得很好,就像预期的那样 - 但现在我需要另一个忽略“ZSTR $”字段的总和。我把这个查询作为CTE的一部分,所以在这个语句中使用它会很好,否则我必须加入表两次并且语句变得很慢。

ErrorCode :(德语):

  

Die ArchivZBEW.PROD.sFCTS_G195.NETTOBETRAG-Spalte ist in derAuswahllistengültig,da sie nicht in einer Aggregatfunktion und nicht in der GROUP BY-Klausel enthalten ist。

感谢谷歌翻译:

  

archiveZBEW.PROD.sFCTS_G195.NETTOBETRAG列在选择列表中无效,因为它不包含在聚合函数中,并且不包含在GROUP BY子句中。

3 个答案:

答案 0 :(得分:5)

在GROUP BY中使用SUM()OVER()没有特别的问题,但是你可能会因为与OVER相关的SUM()的存在而感到困惑,并且忘记它只是需要的另一列发表自己,或在

小组中提到

这不起作用:

SELECT
  a,
  SUM(b),
  SUM(c) OVER(PARTITION BY a) --this wont work: c is not mentioned in GROUP BY and this column is not an aggregate in the GROUP  BY sense
FROM
  table
GROUP BY 
  a

你要么:

SELECT
  a,
  SUM(b),
  SUM(c) OVER(PARTITION BY a)
FROM
  table
GROUP BY 
  a, c --make c something you group by

或者:

SELECT
  a,
  SUM(b),
  SUM(SUM(c) OVER(PARTITION BY a)) --inner sum is overed, outer is groupbyed
FROM
  table
GROUP BY 
  a

或者:

SELECT
  a,
  SUM(b),
  SUM(SUM(c)) OVER(PARTITION BY a) --inner SUM is groupbyed, outer sum is overed
FROM
  table
GROUP BY 
  a

答案 1 :(得分:3)

多数民众赞成 - 谢谢你们 - 这是我的一个重大思想 - 这就是结果:

select  DISTINCT
         ZABF$,ZUNR$,ZONR$,FPLN$,ZSTR$,right(left(GABS$,3),2) as Region

        ,SUM(Nettobetrag) over (partition by ZABF$,ZUNR$,ZONR$,FPLN$,ZSTR$,right(left(GABS$,3),2)) AS NettoUmsatz
        ,SUM(BRUTTOBETRAG) over (partition by ZABF$,ZUNR$,ZONR$,FPLN$,ZSTR$,right(left(GABS$,3),2)) AS BruttoUmsatz
        ,SUM(Nettobetrag) over (partition by ZABF$,ZUNR$,ZONR$,FPLN$,right(left(GABS$,3),2))

    from
         ArchivZBEW.PROD.sFCTS_G195
    where 
        --NETTOBETRAG<>0 
         right(left(GABS$,3),2)<>'65' 
         and UTYP$ in('K','M','P')

答案 2 :(得分:0)

您可以执行以下更改以使代码正常工作:

select  
     ZABF$,ZUNR$,ZONR$,FPLN$,ZSTR$,right(left(GABS$,3),2) as Region

    ,SUM(Nettobetrag) AS NettoUmsatz
    ,SUM(BRUTTOBETRAG) AS BruttoUmsatz
   -- ,SUM(Nettobetrag) over (partition by ZABF$,ZUNR$,ZONR$,FPLN$,right(left(GABS$,3),2)) --commented as this is same as nettoUmsatz

from
     ArchivZBEW.PROD.sFCTS_G195
where 
    --NETTOBETRAG<>0 and  --sum has to be in having
    right(left(GABS$,3),2)<>'65' 
    and UTYP$ in('K','M','P')
group by
    ZABF$,ZUNR$,ZONR$,FPLN$,ZSTR$,right(left(GABS$,3),2)
having SUM(Nettobetrag) <> 0 --you might require this