mysql在select和average之后重命名列值

时间:2012-05-18 04:00:31

标签: mysql

在我当前的表中,我试图获得基于comp_name的列的平均值,下面是输出

    "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"

可以平均“Company1 Pty Ltd”和“Company1 Pty。” (以及其他公司)但添加行数?

我的选择查询在下面,基本上它是根据某个值计算平均值,并根据表格中可用的公司名称进行分组

    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

预期产出:

    "Comp_Name"         "No_of_Rows"    "Column1_Avg"   "Column2_Avg"   "Column3_Avg"
    "Company1"          "1990"          "31"            "68"            "0"
    "Company2"          "18670"         ".."            ".."            "6"
    "Company3"          "2395"          ".."            ".."            ".."

我可以使用某种带有company_name列表的引用表并将其替换吗?

1 个答案:

答案 0 :(得分:2)

如果您只想在GROUP BY子句中使用第一个单词,则可以使用:

GROUP BY CASE LOCATE(' ', Comp_Name) WHEN 0 THEN Comp_Name ELSE LEFT(Comp_Name, LOCATE(' ', Comp_Name)) END

然后,如果你想构建一个引用表,那么像这样的查询应该没问题:

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