【问题标题】:MySQL counts and averages with group byMySQL 使用 group by 计数和平均值
【发布时间】:2011-12-06 22:03:23
【问题描述】:

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

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 必须适合那里的某个地方。提前致谢!

【问题讨论】:

    标签: mysql sql join group-by


    【解决方案1】:
    select area, count(table2.table1_ID) / count(table1.id)
    from table1 left join table2 on table1.id = table2.table1_ID
    group by area
    

    【讨论】:

    • 谢谢!!我在学习。以上是完美的。我添加了一个联合来给我的报告一个总数。
    猜你喜欢
    • 2023-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-12
    • 2017-12-09
    • 1970-01-01
    • 1970-01-01
    • 2015-03-04
    相关资源
    最近更新 更多