在MSAccess中,我有以下查询。当我尝试运行查询时,出现错误Your query does not include the specified expression "ID" as part of aggregate function
,但找不到原因。我的查询出了什么问题?
SELECT
Count(t2.subjectid) AS CountOfsubjectid,
t2.pname,
(
select
max(outcometime)
from
table1 t1
where
t1.id = t2.id
)
AS showntime
FROM
table2 AS t2
WHERE
t2.outcome = "accepted"
GROUP BY
t2.pname,
t2.showntime;
更新(示例数据):
表1:
ID outcometime pname outcome subjectid
1 20181111 USB shown Ux1ku
1 20181113 USB shown Ux1ku
2 20181115 USB shown Tsn2f
3 20181116 USB shown O93nf
2 20181114 USB shown Tsn2f
2 20181112 USB shown Tsn2f
表2:
ID outcometime pname outcome subjectid
1 20181118 USB accepted Ux1ku
2 20181119 USB accepted Tsn2f
3 20181117 USB accepted O93nf
所需结果:
pname showntime countofsubjectid
USB 20181113 1
USB 20181115 1
USB 20181116 1
还更新了示例数据。那是错的。 谢谢。
答案 0 :(得分:0)
如果我理解正确,则需要这样写:
SELECT Count(t2.subjectid) AS CountOfsubjectid,
t2.name,
(select max(outcometime)
from table1 as t1 inner join
table2 as tt2
on t1.id = tt2.id
where tt2.name = t2.name
) as showntime
FROM table2 AS t2
WHERE t2.outcome = "accepted"
GROUP BY t2.name;
答案 1 :(得分:0)
当前,您正在尝试在封装在聚合查询中的SELECT
子句中运行相关子查询,然后在GROUP BY
子句中通过别名引用此子查询。
考虑使用派生表首先通过子查询运行单元级别,然后在外部主查询中运行聚合。
SELECT
dt.pname,
COUNT(subjectid) AS CountOfsubjectid,
dt.showntime
FROM
(SELECT
t2.subjectid
t2.pname,
(
select
max(outcometime)
from
table1 t1
where
t1.id = t2.id
)
AS showntime
FROM
table2 AS t2
WHERE
t2.outcome = 'accepted'
) AS dt
GROUP BY
dt.pname,
dt.showntime;
但是,请考虑避免对表中的每一行运行低效的相关子查询,以加入对MAX
计算的一次的汇总查询,然后再次对{{1} }。
COUNT