BASIC SQL-在分组依据语句和汇总中苦苦挣扎

时间:2018-07-25 12:43:54

标签: sql sql-server group-by aggregate-functions

我正在编写以下SQL脚本,并且遇到上述脚本正下方列出的错误:

  SELECT

       concat(month([sbi].[dtmDelivered]),'-',year([sbi].[dtmDelivered])) as rdate
       ,o.[strCompanyNodeName]
       ,sum(sbi.[mnyDollarcost])
       ,p.[strProductName]
       ,p.[strProductType]
       ,o.[strSalesRegionNodeGroup]
       ,o.[strSalesRegionNodeName]
       ,concat(o.[strMasterSalesFirstNameNode],' ',o.[strMasterSalesLastNameNode]) AS "Sales_Rep"  FROM [sqlSalesBI].[Fact].[uvwReport] as "sbi"

  LEFT JOIN [sqlDim].[dbo].[tbldimProduct] as "p" ON [sbi].[intDimProductPrimaryID] = p.intDimProductID
  LEFT JOIN [sqlSalesBI].[Dim].[uvwOrgNode] as "o" ON [sbi].[intOrgNodeID] = o.intOrgNodeID
  LEFT JOIN [sqlDim].[dbo].[tbldimStatus] as "t" ON [sbi].[intDimStatusID] = t.intDimStatusID

  WHERE sbi.intDimStatusID = 5 and sbi.mnyDollarcost >0 and sbi.dtmDelivered >= '2015-01-01 00:00:00.000'

  GROUP BY o.strCompanyNodeName

执行时出现错误

Msg 8120, Level 16, State 1, Line 3
Column 'sqlSalesBI.Fact.uvwReport.dtmDelivered' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
Msg 8120, Level 16, State 1, Line 3
Column 'sqlSalesBI.Fact.uvwReport.dtmDelivered' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

我最终希望实现的是一个终端表,其中将收入('mnydollarcost')汇总并按月和年('rdate')以及公司('strCompanyNodeName')分组。

这是一张桌子,展示了我希望得到的结果

rdate           strcompanynodename          Sum of MnyDollar Cost         other columns >>>
    ---------------------------------------------------------------------------------- 
7-2017          Chadwick Supply Co.                5100
7-2017          Northeastern Milling               5600
7-2017          Ford Paper                         25320
7-2017          Cleveland Paper Co.                1020
8-2017          Chadwick Supply Co.                1200
8-2017          Northeastern Milling               5600
8-2017          Ford Paper                         58450
8-2017          Cleveland Paper Co.                1200

我对SQL非常陌生,因此,感谢您的耐心等待!

2 个答案:

答案 0 :(得分:0)

看起来您的查询没有得到汇总。将那些缺少的列添加到您的 GROUP BY stmt中,它应可在此处使用。

聚集公式的作用-SELECT子句中的一个字段,然后它必须出现在GROUP BY

答案 1 :(得分:0)

您已经知道,GROUP BY缺少一些:

<tr ng-repeat="user in users | filter: {user.deleted_at == null}" ng-class="{'success': userData.id == user.id }" style="background-color:{{'userData.color'}}" ng-if="selectedRole == '' || (user.group_list | lookup:GROUPS | lists:'name' | join).indexOf(selectedRole) != -1">