Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
250 views
in Technique[技术] by (71.8m points)

optimization - MySQL: Optimizing queries

How can I write this in a more optimized way?

SELECT week_day
     , SUM(min_0 + min_1 + min_2 + min_3) 
     / (SELECT SUM(min_0 + min_1 + min_2 + min_3)
             FROM Hotel.RegIn) * 100 AS MIN_PERCENTAGE
  FROM Hotel.RegIn 
 WHERE week_day = "Wednesday" 
 GROUP 
    BY week_day;

question from:https://stackoverflow.com/questions/65642834/mysql-optimizing-queries

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I'd write it as below:

SELECT
    "Wednesday",
     100 * SUM((week_day = "Wednesday") * (min_0 + min_1 + min_2 + min_3))
        / SUM(min_0 + min_1 + min_2 + min_3) AS MIN_PERCENTAGE
 FROM Hotel.RegIn
;

or if you can use multiple statements, another one with easier filters:

SET @var_all_day_total :=
    (SELECT SUM(min_0 + min_1 + min_2 + min_3) FROM Hotel.RegIn) / 100;

SELECT
    week_day,
    SUM(min_0 + min_1 + min_2 + min_3) / @var_all_day_total AS MIN_PERCENTAGE
FROM Hotel.RegIn
-- WHERE week_day = "Wednesday"
GROUP BY
    week_day
;

The idea usually is not to redundantly calculate the same values more than once.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...