繁体   English   中英

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

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

假设我在 mariadb 中有这张表:

表格1:

Col1 Col2 Col3
测试1 完毕 01-08-2021
测试2 完毕 01-08-2021
测试3 等待 02-08-2021
测试4 完毕 01-08-2021
测试5 失败 01-08-2021
测试6 完成错误 01-08-2021
测试7 完成的 03-09-2021
测试8 因许多错误而失败 10-08-2021
测试9 尚未测试 2021 年 10 月 10 日

我怎样才能进行 sql 查询,这样我就可以有这样的 output :

表2

Col1 Col2
完成的 5
等待完成 2
失败的 2

所以基本上,我想要的是计算 Table1 中包含的行数:Done、Done with errows 或 Finshed,并将该数字写在 Table2 中的Finished行中。 对于 Table1 中包含以下内容的行:Fail 和 Failed with many errors to be written to row Failed in Table2。 对于 Table1 中包含 Waiting 和 Nottested yet to be written to row Waiting to befinished 的 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;

下面演示链接的屏幕截图

演示

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;

最好的方法 - 使用显示的数据创建 static 表statuses并使用它而不是动态子查询。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM