MySQL 使用 group by 进行计数和平均值

发布于 2024-12-19 21:24:42 字数 941 浏览 0 评论 0原文

我会尽力描述。使用错误的数据模型。

Table1
id, name, area, bla1, bla2, bla3

Table2
table1_ID, stuff1, stuff2, ID

trigger on table1
insert row in table2 if table1 is updated

table1 中,我有 10 个不同的区域,只有 186 行,数量不多,我无法使用 Excel 在 2 秒内手动完成此操作,但我想创建实时报告。

报告将是

area1 - %complete
area2 - %complete
area3 - %complete
etc.....

当在 table1 中更新一行时,触发器会在 table2 中插入一些内容,指示“完成”。

我可以做到(可能是非常糟糕的形式)

select
(select count(*) from table1 a where a.id in (select id from table2))
/
(select count(*) from table1)
*100

这给了我一个总体完成百分比。 我正在考虑向每个选择添加 where 子句,硬编码“区域”,然后联合十次。呃,告诉我有一个更好的方法可以在一份报告中得到这个。

显然这个查询是失败的,

select area,
(
(select count(*) from table1 a where a.id in (select id from table2))
/
(select count(*) from table1)
*100) from table1
group by area

我认为 group by 必须适合那里的某个地方。提前致谢!

I'll try and describe best I can. Working with a bad data model.

Table1
id, name, area, bla1, bla2, bla3

Table2
table1_ID, stuff1, stuff2, ID

trigger on table1
insert row in table2 if table1 is updated

In table1 I have 10 different area, only 186 rows, not so much I can't do this manually in like 2 seconds with Excel but I want to create realtime report.

The report would be

area1 - %complete
area2 - %complete
area3 - %complete
etc.....

When a row is updated in table1 the trigger inserts some stuff in table2 indicating 'complete'.

I can do (probably really bad form)

select
(select count(*) from table1 a where a.id in (select id from table2))
/
(select count(*) from table1)
*100

This gives me an overall percentage complete.
I was thinking of adding where clauses to each of the selects, hard coding 'area' and then union TEN times. Ugh, tell me there is a better way to get this in one report.

Obviously this query is a fail

select area,
(
(select count(*) from table1 a where a.id in (select id from table2))
/
(select count(*) from table1)
*100) from table1
group by area

I figure group by has got to fit in there somewhere. Thanks in advance!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

不即不离 2024-12-26 21:24:42
select area, count(table2.table1_ID) / count(table1.id)
from table1 left join table2 on table1.id = table2.table1_ID
group by area
select area, count(table2.table1_ID) / count(table1.id)
from table1 left join table2 on table1.id = table2.table1_ID
group by area
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文