表别名在mysql中不起作用
我的表由一列OPEN_POS1和另一列Lead_time_Bucket组成。我想在三个不同的列中找到提前期为“0到15”、“16到30”和“>30”的所有未结头寸的总和。但是对于以下查询,输出不正确表别名在mysql中不起作用,mysql,sql,Mysql,Sql,我的表由一列OPEN_POS1和另一列Lead_time_Bucket组成。我想在三个不同的列中找到提前期为“0到15”、“16到30”和“>30”的所有未结头寸的总和。但是对于以下查询,输出不正确 select sum(x.OPEN_POS1) as '0-15',sum(y.OPEN_POS1) as '16-30',sum(z.OPEN_POS1) as '>30' from `table 2` as x,`table 2` as y,`table 2` as z where x.
select sum(x.OPEN_POS1) as '0-15',sum(y.OPEN_POS1) as '16-30',sum(z.OPEN_POS1) as '>30'
from `table 2` as x,`table 2` as y,`table 2` as z
where x.Lead_time_Bucket='0 to 15'
and y.Lead_time_Bucket='16 to 30'
and z.Lead_time_Bucket='> 30'
您没有join子句,因此您实际上是在查询
x
每行y
每行z
每行的笛卡尔连接
然而,对于这个用例,您不需要自连接-您可以将sum
与groupby
子句一起使用:
SELECT lead_time_bucket, SUM (open_pos1)
FROM `table 2`
WHERE lead_time_bucket IN ('0 to 15', '16 to 30', '> 30'
GROUP BY lead_time_bucket
只需使用条件聚合。您不需要三个联接:
select sum(case when Lead_time_Bucket = '0 to 15' then OPEN_POS1 else 0 end) as `0-15`,
sum(case when Lead_time_Bucket = '16 to 30' then OPEN_POS1 else 0 end) as `16-30`,
sum(case when Lead_time_Bucket = '> 30' then OPEN_POS1 else 0 end) as `>30`
from `table 2`;
此外:
仅对日期和字符串常量使用单引号。这将防止将来出现问题。而且,如果要使用联接,请学习显式join
语法