Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/74.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
表别名在mysql中不起作用_Mysql_Sql - Fatal编程技术网

表别名在mysql中不起作用

表别名在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.

我的表由一列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'

您没有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
语法