代码之家  ›  专栏  ›  技术社区  ›  Pandurang

concat()在带有count的group_concat()内

  •  0
  • Pandurang  · 技术社区  · 6 年前

    我尝试在mysql中使用group_ccat、concat和count函数获取结果,但它给了我错误。 这是我的桌子

    enter image description here

    首先,当我尝试使用concat获取计数和状态时,它可以正常工作。

    $query="SELECT CONCAT(`status`,':',count(status)) FROM `mytable` GROUP BY status"
    

    输出:
    持有:2
    完成:3
    取消:2

    到这里一切都很好。现在我想把这个输出放在一行中。所以我尝试使用group_concat()。

    $query="SELECT GROUP_CONCAT(CONCAT(`status`,':',count(status)) SEPARATOR ',') as rowString FROM `mytable` GROUP BY status"
    

    但现在它给了我错误 “组函数的使用无效”

    注: 如果我将count(status)替换为表中的其他字段(不带count),则相同的查询也会起作用。这个 count() 以这种方式使用时,函数会导致一些问题。

    期望输出

    保留:2,完成:3,取消:2

    谢谢你的帮助。

    1 回复  |  直到 6 年前
        1
  •  3
  •   sticky bit    6 年前

    不能嵌套聚合函数( count() 在的参数中 group_conat() )一种解决方案是从嵌套的子查询中进行选择。

    SELECT group_concat(status, ':', count SEPARATOR ',') rowstring
           FROM (SELECT status,
                        count(*) count
                        FROM mytable
                        GROUP BY status) x;