我在MySQL中有一个包含以下字段的表。 日期,block_no,实体,阅读
现在我正在解雇这个SQL并获得结果。
SELECT DATE,block_no,
SUM(IF(entity='KS',READING,0)) AS KS,
SUM(IF(entity='KB',READING,0)) AS KB,
SUM(IF(entity='V1',READING,0)) AS V1,
(SUM(IF(entity='KS',READING,0)) + SUM(IF(entity='KB',READING,0)))/SUM(IF(entity='V1',READING,0)) AS "New Rate"
FROM dbf_sdl
GROUP BY DATE,block_no;
这是一个包含三个实体和计算字段的简单查询,但我必须使用它们编写涉及多达15个实体和一些计算字段的查询。有没有办法进一步简化这些查询?字段别名不允许进行计算,例如我无法使用
(KS+KB)/V1 AS "New Rate"
请建议。 感谢
答案 0 :(得分:7)
列别名不能在同一个SELECT语句中使用,但如果您不想重写计算,则可以使用子查询:
select DATE,block_no, KS, KB, V1,
(KS+KB)/V1 AS "New Rate"
from
(
SELECT DATE,block_no,
SUM(IF(entity='KS',READING,0)) AS KS,
SUM(IF(entity='KB',READING,0)) AS KB,
SUM(IF(entity='V1',READING,0)) AS V1
FROM dbf_sdl
GROUP BY DATE,block_no
) d
答案 1 :(得分:2)
您可以在子查询中聚合以避免重复SUM():
SELECT *,(KS+KB)/V1 AS "New Rate"
FROM (SELECT DATE,block_no,
SUM(IF(entity='KS',READING,0)) AS KS,
SUM(IF(entity='KB',READING,0)) AS KB,
SUM(IF(entity='V1',READING,0)) AS V1,
FROM dbf_sdl
GROUP BY DATE,block_no
)as Sub;