1

在我当前的表中,我试图根据 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 列表的某种参考表及其替代吗?

4

1 回答 1

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
来自我的表
按 Simple_Comp_Name 订购
于 2012-05-18T06:10:47.297 回答