即使字段按列表分组也包括分组或聚合错误

时间:2016-01-24 18:33:28

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

我有一个SQL多值分组查询,我想在其中找到字段slt.OUTCOST的最大值。运行它会导致以下错误:

  

专栏'#eldekiSeri.CODE'在选择列表中无效,因为它不包含在聚合函数或GROUP BY子句中。"

即使该字段包含在GROUP BY子句中,我也会收到此错误。

如果我删除MAX聚合并在组列表中包含slt.OUTCOST,则错误消失,但我无法再找到该字段的最大值。

这是我的SQL:

set @sqlAbuk = '
SELECT
eldekiSeri.CODE AS [SERİ NO], 
eldekiSeri.KODU AS [STOK KODU],
eldekiSeri.ACIKLAMA AS [STOK ADI],
clc.CODE AS [CARİ KOD], 
clc.DEFINITION_ AS [CARİ ADI],
MAX(slt.OUTCOST) AS [ALIŞ FİYATI],
stf.DATE_ AS [ALIŞ TARİHİ],
eldekiSeri.AMBARNO AS [ŞUBE KODU]
FROM '+@firmDb+'.dbo.LG_'+@firmNumber+'_'+@firmPeriod+'_SERILOTN sl
INNER JOIN '+@firmDb+'.dbo.LG_'+@firmNumber+'_'+@firmPeriod+'_SLTRANS slt ON sl.LOGICALREF = slt.SLREF
INNER JOIN #eldekiSeri eldekiSeri ON sl.CODE = eldekiSeri.CODE
INNER JOIN '+@firmDb+'.dbo.LG_'+@firmNumber+'_'+@firmPeriod+'_STFICHE stf ON slt.STFICHEREF = stf.LOGICALREF
INNER JOIN '+@firmDb+'.dbo.LG_'+@firmNumber+'_CLCARD clc ON stf.CLIENTREF = clc.LOGICALREF
WHERE (slt.INVENNO = 0) AND (slt.FICHETYPE = 1)';
--print @sqlAbuk;
--exec (@sqlAbuk);
set @sqlAbuk = @sqlAbuk +' AND eldekiSeri.CODE not in ( select distinct bc.[SERİ NO] from #birlestirilmisClone bc ) ';
set @sqlAbuk = @sqlAbuk +' GROUP BY eldekiSeri.CODE, eldekiSeri.KODU, eldekiSeri.ACIKLAMA, clc.CODE, clc.DEFINITION_, stf.DATE_, eldekiSeri.AMBARNO';
set @sqlAbuk = @sqlAbuk +' ORDER BY eldekiSeri.CODE, eldekiSeri.KODU, eldekiSeri.ACIKLAMA, clc.CODE, clc.DEFINITION_, slt.OUTCOST, stf.DATE_, eldekiSeri.AMBARNO';
print @sqlAbuk;
--Exec(@sqlAbuk);
insert into #birlestirilmis Exec(@sqlAbuk);
--print (@sqlAbuk);

1 个答案:

答案 0 :(得分:1)

这是因为你的ORDER BY子句中有slt.OUTCOST。删除它,它将消除您的错误。