[英]mysql how to do an inner join with a second inner join to the same table?
[英]mysql - how do I use the same table in an inner and outer query?
考虑下表
ID | class | 是 |
---|---|---|
1个 | 一种 | 20 |
1个 | 乙 | 50 |
1个 | C | 30 |
1个 | 全部的 | 100 |
我需要生成一个列,表示每个 class 贡献的百分比
就像是
select Y/(select Y from table where class = 'TOTAL')
from table
group by id
但是如何将 id 传递给内部查询?
使用别名你会得到类似的东西:
select
t1.Y/(select t2.Y from table1 t2 where t2.class = 'TOTAL')
from table1 t1
group by t1.id
但这会产生以下错误(参见: DBFIDDLE :
SELECT 列表的表达式 #1 不在 GROUP BY 子句中,并且包含非聚合列“db_1321975282.t1.Y”,它在功能上不依赖于 GROUP BY 子句中的列; 这与 sql_mode=only_full_group_by 不兼容
我认为这就是您的意思,请参阅DBFIDDLE :
select
t1.Y/t2.sumY
from table1 t1
cross join (select sum(y) as sumY from table1 where class='TOTAL') t2
在此查询中, t1
、 t2
和sumY
是别名。
output:
t1.Y/t2.sumY |
---|
0.2000 |
0.5000 |
0.3000 |
1.0000 |
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.