如何比较列并在表中计数

时间:2018-12-28 01:51:09

标签: mysql sql

我正在使用mysql。我需要比较表中的列

我使用MySQL 8.0,并且只有一个数据库

create table A
(
   serial_no           varchar(10),
   p01_pass_fail       varchar(4),
   p02_pass_fail       varchar(4),
   p03_pass_fail       varchar(4),
   p04_pass_fail       varchar(4),
   p05_pass_fail       varchar(4)
)

如果一行是:

serial_no = 001,
p01_pass_fail = pass,
p02_pass_fail = fail,
p03_pass_fail = pass,
p04_pass_fail = pass,
p05_pass_fail = fail

我的理想结果是通过计数= 3,失败计数= 2

这对我来说并不容易

3 个答案:

答案 0 :(得分:2)

您可以使用CASE ... END'pass''fail'“翻译”为10+进行总结。< / p>

SELECT serial_no,
       CASE p01_pass_fail
         WHEN 'fail' THEN
           0
         WHEN 'pass' THEN
           1
       END
       +
       ...
       +
       CASE p05_pass_fail
         WHEN 'fail' THEN
           0
         WHEN 'pass' THEN
           1
       END pass_count,
       CASE p01_pass_fail
         WHEN 'pass' THEN
           0
         WHEN 'fail' THEN
           1
       END
       +
       ...
       +
       CASE p05_pass_fail
         WHEN 'pass' THEN
           0
         WHEN 'fail' THEN
           1
       END fail_count
       FROM a;

答案 1 :(得分:1)

我建议将您的餐桌设计更改为此:

CREATE TABLE A (
    serial_no varchar(10),
    p01_pass_fail tinyint,
    p02_pass_fail tinyint,
    p03_pass_fail tinyint,
    p04_pass_fail tinyint,
    p05_pass_fail tinyint
)

然后,将0存储为失败,将1存储为通过。这大大简化了查询:

SELECT
    serial_no,
    cnt AS pass,
    5 - cnt AS fail
FROM
(
    SELECT,
        serial_no,
        p01_pass_fail + p02_pass_fail + p03_pass_fail + p04_pass_fail + p05_pass_fail AS cnt
    FROM yourTable
) t

标签passfail实际上是表示性的东西,不属于您的数据模型。如果要将整数0/1分数转换为标签,仍可以通过CASE表达式(例如

)进行转换。
CASE WHEN p01_pass_fail = 1 THEN 'pass' ELSE 'fail' END

答案 2 :(得分:1)

另一种方法是制作p01_pass_fail = "pass"之类的布尔表达式,然后将这些表达式的布尔结果求和:

SELECT
    serial_no,
    ((p01_pass_fail = 'pass') +
     (p02_pass_fail = 'pass') +
     (p03_pass_fail = 'pass') +
     (p04_pass_fail = 'pass') +
     (p05_pass_fail = 'pass')) AS pass_count,
    ((p01_pass_fail = 'fail') +
     (p02_pass_fail = 'fail') +
     (p03_pass_fail = 'fail') +
     (p04_pass_fail = 'fail') +
     (p05_pass_fail = 'fail')) AS fail_count
FROM
    A

您还可以使用数据检查下一个样本:DB-Fiddle