[英]SQL - Your query does not include the specified expression as part of an aggregate function
[英]Your query does not include the specified expression “ID” as part of aggregate function
在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
還更新了示例數據。 那是錯的。 謝謝。
如果我理解正確,則需要這樣寫:
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;
當前,您嘗試在封裝在聚合查詢中的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
計算一次 ,然后再次運行聚集COUNT
的主要水平。
SELECT
t2.pname,
COUNT(t.subjectid) AS CountOfsubjectid,
agg.showntime
FROM
table2 AS t2
INNER JOIN
(
select
t1.id,
max(outcometime) as showntime
from
table1 t1
group by
t1.id
) AS agg
ON t2.id = agg.id
WHERE
t2.outcome = 'accepted'
GROUP BY
t2.pname,
agg.showntime;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.