【问题标题】:How to use sum() within a group_concat()?如何在 group_concat() 中使用 sum()?
【发布时间】:2011-01-14 18:12:54
【问题描述】:

问题已修改

真的想要一个 group_concat 的总和...

桌子:商店

+---------+--------+--------+
| shop_id | name   | state  |
+---------+--------+--------+
|    0    | shop 0 |    5   |
|    1    | shop 1 |    5   |
|    2    | shop 2 |    5   |
|    3    | shop 3 |    2   |
+---------+--------+--------+

表格:项目

+------------+--------------+
|   shop  | item | quantity | 
+------------+--------------+
|    0    |  0   |    1     |
|    0    |  1   |    2     |
|    0    |  2   |    3     |
|    1    |  0   |    1     |
|    1    |  1   |    2     |
|    1    |  2   |    3     |
|    2    |  0   |    1     |
|    2    |  1   |    2     |
|    2    |  2   |    3     |
|    3    |  0   |    1     |
|    3    |  1   |    2     |
|    3    |  2   |    3     |
+------------+--------------+

    SELECT state,SUM(i.quantity) total
    FROM shops s2
    LEFT JOIN items i ON i.shop=s2.shopid
    WHERE state=5
    GROUP by item

result #1:

+--------+---------+
| state  |  total  |
+--------+---------+
|    5   |    3    |
+--------+---------+
|    5   |    6    |
+--------+---------+
|    5   |    9    |
+--------+---------+

But I would like the totals, like this:
result #2:
+--------+---------+---------+----------+
| state  | total 0 | total 1 |  total 2 |
+--------+---------+---------+----------+
|    5   |    3    |     6   |    9     |
+--------+---------+---------+----------+

or using group_concat()
result #3

+--------+---------+
| state  | totals  |
+--------+---------+
|    5   |  3,6,9  |
+--------+---------+

我似乎无法让 group_concat 获取结果 #1 中的总列

提前致谢

【问题讨论】:

    标签: mysql sum group-concat


    【解决方案1】:

    变化:

    group_concat(CAST(quantity AS CHAR))
    

    SUM(quantity)
    

    --

    SELECT s.`state`, i.`item`, SUM(i.`quantity`) AS quantities
    FROM `shops` AS s
        LEFT JOIN `items` AS i ON i.`shop` = s.`shopid`
    WHERE s.`state` = 5
    GROUP BY i.`item`
    

    【讨论】:

    • 感谢您的快速回答,这对我最初的要求是正确的,但我问的不是我想要的......
    • @mahks - 我认为你不能只用一个 QUERY 得到你想要的东西
    【解决方案2】:

    据我所知,您无法在 MySQL 中做到这一点。动态列仅在 group_contcat() 的范围内受支持,它仍将多个结果行聚合到单个列中。

    只有当您拥有固定/有限数量的Total X-s 时,您才能在查询中明确声明它们本身。

    【讨论】:

      【解决方案3】:

      找到了一种方法:

      SELECT state,GROUP_CONCAT(cast(total as char))
      FROM
      (
          SELECT state,SUM(i.quantity) total
          FROM shops s
          LEFT JOIN items i ON i.shop=s.shopid
          WHERE state=5
          GROUP by item
      ) s
      

      【讨论】:

        猜你喜欢
        • 2017-10-15
        • 2015-05-26
        • 2010-10-30
        • 2018-07-20
        • 2015-03-24
        • 1970-01-01
        • 2012-05-20
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多