开发者

MySQL count duplicate row

开发者 https://www.devze.com 2023-03-28 00:00 出处:网络
I have a table like this: jobid开发者_如何学Go, orderid And with some data inside: jobid, orderid 1245, 6767

I have a table like this:

jobid开发者_如何学Go, orderid

And with some data inside:

jobid, orderid
1245, 6767
1235, 9058
6783, 6767
4991, 6767
9512, 9058
5123, 1234

Now I want the following output:

jobid, orderid, orderid(total)
1245, 6767, 3
1235, 9058, 2
6783, 6767, 3
4991, 6767, 3
9512, 9058, 2
5123, 1234, 1

Now, the COUNT() doesn't work the way I want to, and I probably need some group by but I don't know how.

Thanks in advance.


It looks like you're trying to get rows which look like jobid, orderid, number of times that orderid appears. For that, you could use a subquery:

 SELECT jobid, orderid, 
        (SELECT COUNT(*) FROM 
         MY_TABLE INR 
             WHERE INR.orderid = OTR.orderid) as "orderid(total)"
 FROM MY_TABLE OTR


Why are doing it this way? You will be doing a lot of redundant countings and put a lot of unnecessary pressure on your server. I would do this with two queries:

SELECT jobid, orderid FROM my_table

to get the complete list, and then:

SELECT orderid, COUNT(*) FROM my_table GROUP BY orderid

to get the total count for each orderid. Then combine these two results in your application. This will be much faster than your solution.


SELECT jobid, orderid, count(orderid)
FROM sometable
GROUP BY orderid, jobid


SELECT t.jobid
     , t.orderid
     , grp.orderid_total
FROM
    tableX AS t
  JOIN
    ( SELECT orderid
           , COUNT(*) AS orderid_total
      FROM tableX
      GROUP BY orderid
    ) AS grp
      ON grp.orderid = t.orderid


select jobid, orderid, count(*) from table group by orderid;
0

精彩评论

暂无评论...
验证码 换一张
取 消