MySQL 使用 group by 进行计数和平均值
我会尽力描述。使用错误的数据模型。
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)