如何根据 sql 中另一个 table 的计数创建新的 table

how to create a new table based on the count from another table in sql

假设我在 mariadb 中有这个 table:

表 1:

Col1 Col2 Col3
Test1 Done 01-08-2021
Test2 Done 01-08-2021
Test3 Waiting 02-08-2021
Test4 Done 01-08-2021
Test5 Fail 01-08-2021
Test6 Done with errors 01-08-2021
Test7 Finished 03-09-2021
Test8 Failed with many errors 10-08-2021
Test9 Not tested yet 10-10-2021

我如何进行 sql 查询才能得到这样的输出:

表 2

Col1 Col2
Finished 5
Waiting to be finished 2
Failed 2

所以基本上,我想要的是计算表 1 中包含的行数:完成、完成但有错误或已完成,并将该数字写在表 2 的 完成 行中. 对于表 1 中包含的行:失败和失败并有许多错误要写入表 2 中的行 Failed。 对于表 1 中包含 Waiting 和 Not tested yet to be written to row Waiting to be finished in Table2.

的行

您可以使用 CASE 表达式进行聚合:

SELECT
    CASE WHEN Col2 IN ('Done', 'Done with errors', 'Finished') THEN 'Finished'
         WHEN Col2 LIKE '%fail%' OR Col2 LIKE '%Fail%' THEN 'Failed'
         WHEN Col2 IN ('Waiting', 'Not tested yet') THEN 'Waiting to be finished'
    END AS Col1,
    COUNT(*) AS Col2
FROM Table1
GROUP BY 1;

Demo

SELECT statuses.col1, COUNT(*)
FROM source_table
JOIN ( SELECT 'Finished' col1, 'Done' col2 UNION ALL
       SELECT 'Finished', 'Done with errors' UNION ALL
       SELECT 'Finished', 'Finished' UNION ALL 
       SELECT 'Failed', 'Fail' UNION ALL 
       SELECT 'Failed', 'Failed with many errors' UNION ALL 
       SELECT 'Waiting to be finished', 'Waiting' UNION ALL 
       SELECT 'Waiting to be finished', 'Not tested yet' ) statuses USING (col2)
GROUP BY statuses.col1;

最佳方法 - 使用显示的数据创建静态 table statuses 并使用它代替动态子查询。