MySQL GROUP BY and COUNT

微笑、不失礼 提交于 2020-01-04 09:43:51

问题


I have a small problem regarding a count after grouping some elements from a mysql table, I have an orders table .. in which each order has several rows grouped by a code (named as codcomanda) ... I have to do a query which counts the number of orders per customer and lists only the name and number of orders.

This is what i came up (this might be dumb ... i'm not a pro programmer)

SELECT a.nume, a.tel, (
    SELECT COUNT(*) AS `count` 
      FROM (
        SELECT id AS `lwtemp` 
          FROM lw_comenzi_confirmate AS yt 
         WHERE status=1 AND yt.tel LIKE **a.tel** 
         GROUP BY yt.codcomanda
      ) AS b
  ) AS numar_comenzi 
  FROM lw_comenzi_confirmate AS a 
 WHERE status=1 
 GROUP BY tel;

nume = NAME
tel = PHONE (which is the distinct identifier for clients since there's no login system)

The problem with the above query is that I don't know how to match the a.tel with the one on which the first select is on. If I replace it with a number that is in the db it works....

Can anyone help me one how to refer to that var? or maybe another solution on how to get this done?

If any more info is needed I`ll provide asap.


回答1:


Please, correct me if I'm wrong in my understanding of your schema:

  • lw_comenzi_confirmate contains nume and tel of the customer;
  • lw_comenzi_confirmate contains order details (same table);
  • one order can have several entries in the lw_comenzi_confirmate table, order is distinguished by codcomanda field.

First, I highly recommend reading about Normalisation and fixing your database design.

The following should do the job for you:

SELECT nume, tel, count(DISTINCT codcomanda) AS cnt
  FROM lw_comenzi_confirmate
 WHERE status = 1
 GROUP BY nume, tel
 ORDER BY nume, tel;

You can test this query on SQL Fiddle.



来源:https://stackoverflow.com/questions/10599789/mysql-group-by-and-count

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!