dongmao3131 2014-08-21 08:04
浏览 40

如何使用group by,distinct和sum?

I have 1 table: temp_shoppingcart .

In the temp_shoppingcart, i have temp_shoppingcart_id, user_id, product_id, quantity and color. Anytime, a user add an item in the shopping cart, it will add a new row to store the data.

So the data will have something like user_id: 1, product_id: 123, quantity: 1, color: black. If the user add the same item again, it will have the same data entered as a new row. So there will be the same row twice.

How do I display the data such that the same product will be group together as display as the same row but the quantity is the sum of 2 rows?

  • 写回答

1条回答 默认 最新

  • duan41497 2014-08-21 08:45
    关注

    That's a pretty basic query concept actually. Maybe you can look at some MySQL tutorial and learn a bit more. Something like this: http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html

    Anyway the query below

    SELECT product_id,SUM(quantity),GROUP_CONCAT(color)
    FROM table
    GROUP BY product_id

    would display a row with the sum qty. The GROUP_CONCAT(color) will display for example, "red,red" if both entries "color" field are red.

    I would suggest the query below if you want to group items by colors too.

    SELECT user_id,product_id,color,SUM(quantity)
    FROM temp_shoppingcart
    GROUP BY user_id, product_id,color

    If you don't want to group by colors

    SELECT user_id,product_id,GROUP_CONCAT(color),SUM(quantity)
    FROM temp_shoppingcart
    GROUP BY user_id, product_id

    评论

报告相同问题?

悬赏问题

  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用