0

我在 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"

请建议。谢谢

4

2 回答 2

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
于 2013-06-18T17:25:13.320 回答
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;
于 2013-06-18T17:25:37.747 回答