在2个内连接之后的SQL Group by外部引用

时间:2018-04-04 12:16:46

标签: sql .net sql-server sql-server-2012

我的sql查询没有按预期工作,它以当前形式返回结果,但第二个列中的一些是重复的,换句话说,一些计算机名称后跟驱动器号显示两次。

查询是这样的:

(select Distinct 'ServerDrive' as storageType, cast(assetname as 
varchar)+ '\ ' +cast(caption as varchar) as storagePath,((rqDiskdrivesHist. 
[size]-rqDiskdrivesHist.[freespace])/1024/1024) as usedMB,(rqDiskdrivesHist. 
[size]/1024/1024) as sizeMB from lansweeperdb.dbo.tblAssets 
inner join rqDiskdrivesHist
on lansweeperdb.dbo.tblAssets.AssetID=rqDiskdrivesHist.AssetID 
where drivetype=3
and lansweeperdb.dbo.tblAssets.AssetName in
(select distinct entitypath from rqcentities
inner join rqcustomer
on rqcentities.customerID=rqcustomer.customerID 
where customername like '%ak 26%' and entityType='computer'
and not (
(AssetName like 'WFP3675' and caption like 'D:')
or
(AssetName like 'WFP3675' and caption like 'E:')
or
(AssetName like 'WFP3675' and caption like 'F:')
or
(AssetName like '%00500%')
)  
)) 

如果我尝试在最后分组。用:

GROUP BY cast(assetname as varchar)+'\'+cast(caption as varchar)

我将得到"每个GROUP BY表达式必须包含至少一个不是外部引用的列。 "错误。

编辑:这些是重复结果的两行。

enter image description here

1 个答案:

答案 0 :(得分:0)

您需要对别名进行分组,因为您没有在内部查询中公开这些字段。

SELECT
    storageType,
    storagePath,
    MaxMB = MAX(usedMB),
    MinMB = MIN(usedMB),
    AvgMB = AVG(usedMB)
FROM
(
    select 'ServerDrive' as storageType, 
    cast(assetname as varchar)+ '\ ' +cast(caption as varchar) as storagePath,
    ((rqDiskdrivesHist.[size]-rqDiskdrivesHist.[freespace])/1024/1024) as usedMB,
    (rqDiskdrivesHist.[size]/1024/1024) as sizeMB 
    from 
        lansweeperdb.dbo.tblAssets 
        inner join rqDiskdrivesHist on lansweeperdb.dbo.tblAssets.AssetID=rqDiskdrivesHist.AssetID 
    where 
        drivetype=3
        and lansweeperdb.dbo.tblAssets.AssetName in
        (
            select distinct entitypath 
            from rqcentities
            inner join rqcustomer on rqcentities.customerID=rqcustomer.customerID 
            where customername like '%ak 26%' and entityType='computer'
            and not (
                        (AssetName like 'WFP3675' and caption like 'D:')
                        or
                        (AssetName like 'WFP3675' and caption like 'E:')
                        or
                        (AssetName like 'WFP3675' and caption like 'F:')
                        or
                        (AssetName like '%00500%')
                    )  
        )
) AS X
GROUP BY
    storagePath,
    storageType