简体   繁体   中英

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

Lets say that i have this table in mariadb:

Table1:

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

How can i make an sql query so i can have an output like this:

Table2

Col1 Col2
Finished 5
Waiting to be finished 2
Failed 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. For the rows in Table1 that contain: Fail and 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.

You may aggregate using a CASE expression:

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;

The best way - create static table statuses with shown data and use it instead of dynamic subquery.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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