2014-09-24 47 views
2

我的表由OPEN_POS1列和另一列Lead_time_Bucket组成。我想在三个不同的列中找到所有OPEN_POS1与Lead_time_Bucket'0到15','16到30'和'> 30'的总和。但是输出对于下面的查询是不正确的。表别名不工作在mysql

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

只需使用条件聚集。你并不需要三个联接:

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

+0

谢谢!它的工作! :) – 2014-09-24 10:56:22

0

你没有连接子句,所以你有效地查询笛卡儿连接的zy次,每次行x次各行的每一行的。

对于这个用例,但是,你并不需要自连接 - 你可以只使用sumgroup by条款:

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 
+0

谢谢!它的工作! :) – 2014-09-24 10:50:51