所以我一直在研究一系列的sql命令/报告。我尝试获取特定个人创建的总事件的总和,然后在事件发生时每天增加。因此,如果Tim在1天内发生事故,然后在下一天发生0事件,那么在第二天发生事故,那么它将在3起事件中显示他的名字。
实施例: 表A
Tim | 1 | day one
Tim | 0 | day two
Tim | 2 | day three
表B
Tim | 3 | week1
以下是我尝试的一些SQL命令:
INSERT INTO WeeklyReport(ImportDate, DayofData, [Name], TotalA, TotalB, TotalC)
SELECT GETDATE() AS ImportDate, DATEADD(day, -1, GETDATE()) AS DayofData, p.[Name], SUM(p.IncidentA), SUM(c.IncidentB), SUM(n.IncidentC)
FROM TableA p
INNER JOIN TableB c ON c.[Name] = p.[Name]
INNER JOIN TableC n ON n.[Name] = p.[Name]
我遇到了这个错误:
Msg 8120,Level 16,State 1,Line 2 Column' TableA.Name'在...中无效 选择列表,因为它不包含在聚合中 函数或GROUP BY子句。
可以对命令进行哪些更改以更好地适应此错误?
答案 0 :(得分:2)
非常基本的事情,当non-aggregate
列表中使用Group by
函数时,您需要在Aggregate
中添加Select
列
INSERT INTO weeklyreport
(importdate,
dayofdata,
[name],
totala,
totalb,
totalc)
SELECT Getdate() AS ImportDate, --Constant so allowed
Dateadd(day, -1, Getdate()) AS DayofData, --Constant so allowed
p.[name], -- Non Aggregate column should be present in Group by
Sum(p.incidenta),
Sum(c.incidentb),
Sum(n.incidentc)
FROM tablea p
INNER JOIN tableb c
ON c.[name] = p.[name]
INNER JOIN tablec n
ON n.[name] = p.[name]
GROUP BY P.[name]