计算总 SQL 的百分比 (%)

时间:2021-04-16 23:13:27

标签: mysql sql

如何使用查询来执行以下操作:

  • 获取用户在特定日期输入的所有记录 (SELECT count(*) from table WHERE user = "root" and date(dt) = NOW())
  • 当任何字段为空时,获取用户在某个日期输入的所有记录( (SELECT count(*) from table WHERE user = "root" and field1 = "" and date(dt) = NOW()))
  • 返回包含空字段的记录百分比

SQL 表

 -- phpMyAdmin SQL Dump
-- version 5.0.2
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1:3306
-- Tempo de geração: 16-Abr-2021 às 23:17
-- Versão do servidor: 5.7.31
-- versão do PHP: 7.3.21

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
START TRANSACTION;
SET time_zone = "+00:00";


/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;

--
-- Banco de dados: `db_test`
--

-- --------------------------------------------------------

--
-- Estrutura da tabela `tbl`
--

DROP TABLE IF EXISTS `tbl`;
CREATE TABLE IF NOT EXISTS `tbl` (
  `user` varchar(255) NOT NULL,
  `field1` varchar(255) NOT NULL,
  `dt` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Extraindo dados da tabela `tbl`
--

INSERT INTO `tbl` (`user`, `field1`, `dt`) VALUES
('root', 'not empty', '2021-04-17 00:17:27'),
('root', '', '2021-04-17 00:17:27');
COMMIT;

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;

示例表

+------+-----------+
| user |  field1   |
+------+-----------+
| root | not empty |
| root |           |
+------+-----------+

预期输出

+------+-------------------------------------+
| user | perc_register_that_have_empty_field |
+------+-------------------------------------+
| root |                                  50 |
+------+-------------------------------------+

1 个答案:

答案 0 :(得分:0)

你可以计算一个表达式。例如:

SELECT 
  sum(case when field1 = '' or field1 is null then 1 else 0 end) /
  count(*) as perc_register_that_have_empty_field
from t 
WHERE user = 'root' and date(dt) = curdate()

结果:

 perc_register_that_have_empty_field 
 ----------------------------------- 
 0.4000                              

请参阅 DB Fiddle 上的运行示例。