在存储过程中,我有一个临时表@Branches
。我将值插入@Branches
中,表结构如下:
declare @Branches table( BranchId int, BranchName varchar(60))
BranchID BranchName IsActive
--------------------------------
16 New Delhi 1
17 Panjab 0
在我的数据库中,有一个名为lobby
的表及其数据,如下所示,
QueueID FkBranch IsActive Status AddedLocalTime FkAssistTypeID
553279 16 1 5 7/12/2019 2
553278 16 1 5 7/12/2019 1
553277 16 1 5 7/12/2019 1
553276 16 1 5 7/12/2019 1
553275 16 1 5 7/12/2019 2
553274 16 1 5 7/9/2019 2
我需要根据其值来计算FkAssistTypeID
的数量,我退出了该脚本
declare @BranchDetail table (Id int, Name varchar(60), TotalInteraction float, AssistCount float)
insert into @BranchDetail
select b.BranchId as Id, b.BranchName as Name,
count(lo.LobbyId) TotalInteraction,
count(case WHEN lo.FkAssistTypeID = 1 then 1 end) as AssistCount
from
@Branches b
left outer join
(select br.BranchId, l.LobbyId, l.FkAssistTypeID
from lobby l
left outer join @Branches br on l.FkBranchId = br.BranchId
where l.AddedLocalTime >= @startDate
and l.AddedLocalTime <= CONVERT(VARCHAR, @endDate, 101) + ' 23:59:59'
and l.IsActive = 1
group by br.BranchId, l.LobbyId) lo on lo.BranchId = b.BranchId
group by
b.BranchId, b.BranchName
order by
b.BranchName
select @AvgInteractions= COALESCE( Convert(decimal(18,2), AVG(TotalInteraction)),0) from @BranchDetail
update @BranchDetail
SET AverageInteractions =@AvgInteractions from @BranchDetail
select * from @BranchDetail
我收到此错误
消息8120,级别16,状态1,过程spGetActComDetails,第228行[批处理开始第7行]
列'lobby.FkAssistTypeId'在选择列表中无效,因为它既不包含在聚合函数中,也不包含在GROUP BY子句中。
但是,如果我在上述查询中使用的所有地方都删除了FkAssistTypeID
,则查询可以正常工作并获取该输出。
但是我需要这个
如何解决这个问题?
答案 0 :(得分:1)
尝试:
insert into @BranchDetail
select b.BranchId as Id,b.BranchName as Name,count(lo.LobbyId) TotalInteraction,
SUM(case WHEN lo.FkAssistTypeID = 1 THEN 1 ELSE 0 END) as AssistCount
from @Branches b
left outer join
(
select br.BranchId,l.LobbyId,l.FkAssistTypeID
from lobby l
left outer join @Branches br on l.FkBranchId=br.BranchId
where l.AddedLocalTime >=@startDate and ( l.AddedLocalTime ) <= CONVERT(VARCHAR, @endDate, 101)+ ' 23:59:59'and l.IsActive=1
group by br.BranchId,l.LobbyId,l.FkAssistTypeID) lo on lo.BranchId=b.BranchId
group by b.BranchId,b.BranchName
order by b.BranchName
您需要使用SUM
而不是COUNT
,因为COUNT:
COUNT(*)返回一个组中的项目数。这包括NULL 值和重复项。