Advertisement
rgruber

mysql histogram function

Dec 25th, 2022
1,611
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
MySQL 0.75 KB | None | 0 0
  1. DELIMITER //
  2. CREATE FUNCTION histogram(col INT, bins INT) RETURNS TABLE (bin_number INT, bin_left INT, bin_right INT, bin_frequency INT)
  3. BEGIN
  4.     DECLARE min, max, bin_size INT;
  5.  
  6.     SELECT MIN(col) INTO min, MAX(col) INTO max FROM table;
  7.     SET bin_size = (max - min) / bins;
  8.  
  9.     CREATE TEMPORARY TABLE hist (bin_number INT, bin_left INT, bin_right INT, bin_frequency INT);
  10.     INSERT INTO hist (bin_number, bin_left, bin_right, bin_frequency)
  11.     SELECT FLOOR((col - min) / bin_size) AS bin_number,
  12.            MIN(col) + bin_number * bin_size AS bin_left,
  13.            MIN(col) + (bin_number + 1) * bin_size AS bin_right,
  14.            COUNT(*) AS bin_frequency
  15.     FROM table
  16.     GROUP BY bin_number;
  17.  
  18.     RETURN SELECT * FROM hist;
  19. END//
  20. DELIMITER ;
  21.  
Tags: histogram
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement