我有以下sql查询,我只想要一个列的总和但是它的相同记录的多个回复如下
SELECT
b.[Name]
sum(td.detailNumber) over () as Totaldetail,
sum(t.Original) over () as TotalOriginal
FROM Detail td WITH(NOLOCK)
inner JOIN Ticket t WITH(NOLOCK) ON t.ID = td.ID
inner JOIN [system].Branch b WITH(NOLOCK) ON t.BranchID = b.BranchID
inner JOIN Option mo WITH(NOLOCK) ON OptionID = td.MID
WHERE (td.ResultDateTime >= '2018/03/10 00:00:00:000' AND td.ResultDateTime <= '2018/03/10 23:59:59:000')
AND t.BranchID IN (SELECT Data FROM [system].Split('37', ','))
AND t.Code IN ('RS','AC')
结果
Totaldetail | Totaloriginal
54868 | 78569
54868 | 78569
54868 | 78569
54868 | 78569
54868 | 78569
54868 | 78569
54868 | 78569
正如你在上面看到的那样,它显示了我提供的日期的多行。我只想一次一个结果
Totaldetail | Totaloriginal
54868 | 78569 //only one record to be shown
答案 0 :(得分:0)
首先,删除你OVER
条款。 OVER()
子句使您的SUM
成为一个窗口函数,因此它不会对任何内容进行分组。这就是为什么你看到没有分组的行。
如果您想按每个名称查看聚合,请添加GROUP BY
。
SELECT
b.[Name],
sum(td.detailNumber) as Totaldetail,
sum(t.Original) as TotalOriginal
FROM Detail td WITH(NOLOCK)
inner JOIN Ticket t WITH(NOLOCK) ON t.ID = td.ID
inner JOIN [system].Branch b WITH(NOLOCK) ON t.BranchID = b.BranchID
inner JOIN Option mo WITH(NOLOCK) ON OptionID = td.MID
WHERE (td.ResultDateTime >= '2018/03/10 00:00:00:000' AND td.ResultDateTime <= '2018/03/10 23:59:59:000')
AND t.BranchID IN (SELECT Data FROM [system].Split('37', ','))
AND t.Code IN ('RS','AC')
GROUP BY
b.[Name]
如果您只想查看总计,请删除b。[name]列。
SELECT
sum(td.detailNumber) as Totaldetail,
sum(t.Original) as TotalOriginal
FROM Detail td WITH(NOLOCK)
inner JOIN Ticket t WITH(NOLOCK) ON t.ID = td.ID
inner JOIN [system].Branch b WITH(NOLOCK) ON t.BranchID = b.BranchID
inner JOIN Option mo WITH(NOLOCK) ON OptionID = td.MID
WHERE (td.ResultDateTime >= '2018/03/10 00:00:00:000' AND td.ResultDateTime <= '2018/03/10 23:59:59:000')
AND t.BranchID IN (SELECT Data FROM [system].Split('37', ','))
AND t.Code IN ('RS','AC')