[英]how to create a new table based on the count from another table in sql
Lets say that i have this table in mariadb:假设我在 mariadb 中有这张表:
Table1:表格1:
Col1 Col1 | Col2 Col2 | Col3 Col3 |
---|---|---|
Test1测试1 | Done完毕 | 01-08-2021 01-08-2021 |
Test2测试2 | Done完毕 | 01-08-2021 01-08-2021 |
Test3测试3 | Waiting等待 | 02-08-2021 02-08-2021 |
Test4测试4 | Done完毕 | 01-08-2021 01-08-2021 |
Test5测试5 | Fail失败 | 01-08-2021 01-08-2021 |
Test6测试6 | Done with errors完成错误 | 01-08-2021 01-08-2021 |
Test7测试7 | Finished完成的 | 03-09-2021 03-09-2021 |
Test8测试8 | Failed with many errors因许多错误而失败 | 10-08-2021 10-08-2021 |
Test9测试9 | Not tested yet尚未测试 | 10-10-2021 2021 年 10 月 10 日 |
How can i make an sql query so i can have an output like this:我怎样才能进行 sql 查询,这样我就可以有这样的 output :
Table2表2
Col1 Col1 | Col2 Col2 |
---|---|
Finished完成的 | 5 5 |
Waiting to be finished等待完成 | 2 2 |
Failed失败的 | 2 2 |
So baically, what i want is to count the numbers of rows in Table1 which contain: Done, Done with errows or Finshed and to write that number in row Finished in Table2.所以基本上,我想要的是计算 Table1 中包含的行数:Done、Done with errows 或 Finshed,并将该数字写在 Table2 中的Finished行中。 For the rows in Table1 that contain: Fail and Failed with many errors to be written to row Failed in Table2.对于 Table1 中包含以下内容的行:Fail 和 Failed with many errors to be written to row Failed in Table2。 For the rows in Table1 that contain Waiting and Not tested yet to be written to row Waiting to be finished in Table2.对于 Table1 中包含 Waiting 和 Nottested yet to be written to row Waiting to befinished 的 Table2 中的行。
You may aggregate using a CASE
expression:您可以使用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;
The best way - create static table statuses
with shown data and use it instead of dynamic subquery.最好的方法 - 使用显示的数据创建 static 表statuses
并使用它而不是动态子查询。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.