简体   繁体   中英

How can I use subquery without WITH?

SELECT  Agegroup, Attrition, Attrition / (SELECT Count(Attrition) FROM project1.employee) * 100 as Attrition_rate
from (SELECT Agegroup, Count(*) as Attrition
   FROM(Select
    CASE
        WHEN age BETWEEN 0 AND 20 THEN '<20'
        WHEN age BETWEEN 20 AND 29 THEN '20-29'
        WHEN age BETWEEN 30 AND 39 THEN '30-40'
        WHEN age BETWEEN 40 AND 49 THEN '40-50'
        WHEN age BETWEEN 50 AND 100 THEN 'Greater than 50'
        ELSE 'not specified'
    END AS Agegroup
    FROM project1.employee
    Where Attrition = TRUE) AS T
    GROUP BY Agegroup) AS TT
ORDER BY Agegroup;

This returns zero results, but when I use WITH Clause in BigQuery it works fine. WITH CLAUSE is not working in mySQL workbench

Both mysql and BigQuery allow with clauses. Maybe your data is different in these systems? Please provide mySQL version details.

Please consider using windows function with over instead of nested queries. Tested in BiqQuery:

With employee as 
(Select 19 age, true Attrition 
union all select 20,true
union all select 50,true)

SELECT  Agegroup, Attrition, Attrition / sum(Attrition) over ()
from (SELECT Agegroup, Count(*) as Attrition
   FROM(Select
    CASE
        WHEN age BETWEEN 0 AND 20 THEN '<20'
        WHEN age BETWEEN 20 AND 29 THEN '20-29'
        WHEN age BETWEEN 30 AND 39 THEN '30-40'
        WHEN age BETWEEN 40 AND 49 THEN '40-50'
        WHEN age BETWEEN 50 AND 100 THEN 'Greater than 50'
        ELSE 'not specified'
    END AS Agegroup
    FROM  employee
    Where Attrition = TRUE) AS T
    GROUP BY Agegroup) AS TT
ORDER BY Agegroup;

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