当我尝试在Microsoft Access中运行此SQL SELECT语句时,我收到一条错误消息:
SELECT (tblBestelldetails.Einzelpreis * tblBestelldetails.Anzahl) AS Barwert
, tblKunden.Firma, Count(tbl.BestellungID)
FROM (tblBestellungen
INNER JOIN tblBestelldetails
ON tblBestellungen.BestellungID = tblBestelldetails.BestellungID)
INNER JOIN tblKunden
ON tblBestellungen.KundeID = tblKunden.KundeID;
一旦我将Count(tbl.BestellungID)
字段添加到SELECT语句中,它就会失败。此外,我知道我必须在BestellungID
稍后对其进行分组,但我尝试了这一点并没有解决我的问题。
奇怪的是,一旦我添加了Count(tbl.BestellungID)
它就说
参数(tblBestelldetails.Einzelpreis * tblBestelldetails.Anzahl)AS Barwert不起作用,因为它不是聚合函数。
有人知道如何解决这个问题吗?
答案 0 :(得分:3)
您需要按所有非聚合字段进行分组。
除非您添加总和(或其他聚合),否则 (tblBestelldetails.Einzelpreis * tblBestelldetails.Anzahl)
不是聚合,因此您必须按照select中的相同公式进行分组。无法在聚合中使用别名,因为在DB引擎评估group by时不知道别名。因此,您需要在组中包含公式。
SELECT (tblBestelldetails.Einzelpreis * tblBestelldetails.Anzahl) AS Barwert
, tblKunden.Firma
, Count(tblBestellungen .BestellungID)
FROM (tblBestellungen
INNER JOIN tblBestelldetails
ON tblBestellungen.BestellungID = tblBestelldetails.BestellungID)
INNER JOIN tblKunden
ON tblBestellungen.KundeID = tblKunden.KundeID
GROUP BY (tblBestelldetails.Einzelpreis * tblBestelldetails.Anzahl)
, tblKunden.Firma
也许你需要聚合barwert .. 看起来你在tblBestellungen-tblBestelldetails - tblKunden之间有1-M-1的关系。
所以也许我们只需要聚合细节并按照分类进行分组。
SELECT sum(tblBestelldetails.Einzelpreis * tblBestelldetails.Anzahl) AS Barwert
, tblKunden.Firma
, Count(tblBestellungen.BestellungID)
FROM (tblBestellungen
INNER JOIN tblBestelldetails
ON tblBestellungen.BestellungID = tblBestelldetails.BestellungID)
INNER JOIN tblKunden
ON tblBestellungen.KundeID = tblKunden.KundeID
GROUP BY tblKunden.Firma
或....也许你没有强制执行数据库完整性并需要区分ID?
SELECT (tblBestelldetails.Einzelpreis * tblBestelldetails.Anzahl) AS Barwert
, tblKunden.Firma
, Count(distinct tblBestellungen.BestellungID)
FROM (tblBestellungen
INNER JOIN tblBestelldetails
ON tblBestellungen.BestellungID = tblBestelldetails.BestellungID)
INNER JOIN tblKunden
ON tblBestellungen.KundeID = tblKunden.KundeID
GROUP BY (tblBestelldetails.Einzelpreis * tblBestelldetails.Anzahl)
, tblKunden.Firma