2014-09-24 84 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