In my current table i am trying to get average of columns based on comp_name and below is the output
"Comp_Name" "No_of_Rows" "Column1_Avg" "Column2_Avg" "Column3_Avg"
"Company1 Pty Ltd" "291" "39" "60" "0"
"Company1 Pty." "1699" "23" "76" "0"
"Company2 Ltd" 14335" "6" "82" "10"
"Company2 " "4335" "60" "8" "2"
"Company3 Pty Ltd" "767" "22" "77" "0"
"Company3" "1628" "16" "82" "1"
Is is possible to average “Company1 Pty Ltd” and “Company1 Pty.” (and for the other companies) but add the number of rows?
My select query is below and basically it is calculating average based on a certain value and grouping based on the company name available in the table
SELECT Comp_Name,count(*) as No_of_Rows,
CAST( (COUNT(CASE WHEN Column1 < 500 then 1 else NULL end)/COUNT(mytable.ID)) * 100 AS CHAR(2))+'%' as Column1_Avg,
CAST( (COUNT(CASE WHEN (Column1 < 30000 AND Column1 > 500) then 1 else NULL end)/COUNT(mytable.ID)) * 100 AS CHAR(2))+'%' as Column2_Avg,
CAST( (COUNT(CASE WHEN (Column1 > 30000) then 1 else NULL end)/COUNT(mytable.ID)) * 100 AS CHAR(2))+'%' as Column3_Avg
FROM mytable
GROUP BY Comp_Name desc
Expected output:
"Comp_Name" "No_of_Rows" "Column1_Avg" "Column2_Avg" "Column3_Avg"
"Company1" "1990" "31" "68" "0"
"Company2" "18670" ".." ".." "6"
"Company3" "2395" ".." ".." ".."
Can i use some sort of reference table with a list of company_name and it’s substitution?
If you want to only take the first word in your
GROUP BYclause, you can use:GROUP BY CASE LOCATE(' ', Comp_Name) WHEN 0 THEN Comp_Name ELSE LEFT(Comp_Name, LOCATE(' ', Comp_Name)) ENDThen, if you want to build a reference table, a query like this should be fine:
SELECT DISTINCT Comp_Name, CASE LOCATE(' ', Comp_Name) WHEN 0 THEN Comp_Name ELSE LEFT(Comp_Name, LOCATE(' ', Comp_Name)) END AS Simple_Comp_Name FROM mytable ORDER BY Simple_Comp_Name