表别名在mysql中不起作用

时间:2014-09-24 10:36:20

标签: mysql sql

我的表包含一列OPEN_POS1和另一列Lead_time_Bucket。我想找到所有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.Lead_time_Bucket='0 to 15'
and y.Lead_time_Bucket='16 to 30'
and z.Lead_time_Bucket='> 30'

2 个答案:

答案 0 :(得分:2)

只需使用条件聚合。您不需要三个连接:

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语法。

答案 1 :(得分:0)

您没有加入子句,因此您有效查询x每行yz次每行sum次的笛卡尔联接。

但是,对于此用例,您不需要自联接 - 您可以将group bySELECT 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 子句一起使用:

{{1}}