如何使用SQL Server中的别名按多列分组?

时间:2015-09-29 18:41:45

标签: sql sql-server

从一些旧代码中获取查询,我试图让它工作。每次我提交查询时都会收到错误:

  

错误代码207,SQL状态S0001:列名无效'等级'

代码:

SELECT 
    COUNT(*) AS PieceCount
    ,shifttimes.shiftid AS ShiftId
    ,specienames.NameText AS Specie
    ,gradenames.NameText AS Grade
    ,DryerNum
    ,CreatedLocal
FROM 
    sheets, shifttimes, Specienames, GradeNames
WHERE 
    sheets.ShiftIndex = shifttimes.ShiftIndex
    AND sheets.SpecieNameIndex = specienames.NameIndex
    AND sheets.gradenameindex = gradenames.NameIndex
    AND CreatedLocal >= '2015-04-01'
    AND CreatedLocal < '2015-06-01'
GROUP BY 
    ShiftId, Grade, DryerNum, Specie

1 个答案:

答案 0 :(得分:5)

对于错误,我认为你应该改变

GROUP BY ShiftId
    ,Grade
    ,DryerNum
    ,Specie

TO

GROUP BY shifttimes.shiftid
    ,gradenames.NameText
    ,DryerNum
    ,specienames.NameText

注意:

在您选择,CreatedLocal但未在group by中选择时,您必须将其从选择中移除或包含在group by

<强>建议:

尝试使用Alias和Implicit连接(在from子句中有两个表)是一种不推荐使用的语法,建议切换到现代的显式语法:

SELECT COUNT(*) AS PieceCount
    ,ST.shiftid AS ShiftId
    ,SN.NameText AS Specie
    ,GN.NameText AS Grade
    ,DryerNum    
FROM 
   sheets S
inner join shifttimes ST
   ON S.ShiftIndex = ST.ShiftIndex
inner join Specienames SN
   ON S.SpecieNameIndex = SN.NameIndex
inner join GradeNames GN
   ON S.gradenameindex = GN.NameIndex
WHERE 
    CreatedLocal >= '2015-04-01'
AND CreatedLocal < '2015-06-01'
GROUP BY 
     ST.shiftid
    ,GN.NameText
    ,DryerNum
    ,SN.NameText