[英]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.