简体   繁体   中英

MySQL distinct, group_concat and count question

I have a table.

+----------+----------------+--------+
| orderid  | barcode        | status |
+----------+----------------+--------+
| R-R34184 | K2020101500001 |      1 |
| R-R34184 | K2020101500001 |      1 |
| R-R34184 | K2020101500001 |      0 |
| R-R34184 | K2020101500001 |      0 |
| R-R34184 | K2020101500002 |      2 |
| R-R34184 | K2020101500002 |      2 |
| R-R34184 | K2020101500002 |      2 |
| R-R34184 | K2020101500002 |      2 |
| R-R34184 | K2020101500003 |      1 |
| R-R34184 | K2020101500003 |      1 |
| R-R34184 | K2020101500003 |      0 |
| R-R34184 | K2020101500003 |      0 |
| R-R34185 | K2020101500005 |      0 |
| R-R34185 | K2020101500005 |      0 |
| R-R34185 | K2020101500005 |      0 |
| R-R34185 | K2020101500005 |      0 |
| R-R34185 | K2020101500006 |      0 |
| R-R34185 | K2020101500006 |      0 |
| R-R34185 | K2020101500006 |      0 |
| R-R34185 | K2020101500006 |      0 |
| R-R34185 | K2020101500004 |      0 |
| R-R34185 | K2020101500004 |      0 |
| R-R34185 | K2020101500004 |      0 |
| R-R34185 | K2020101500004 |      0 |
| R-R34185 | K2020101500007 |      0 |
| R-R34185 | K2020101500007 |      0 |
| R-R34185 | K2020101500007 |      0 |
| R-R34185 | K2020101500007 |      0 |
| R-R34185 | K2020101500008 |      0 |
| R-R34185 | K2020101500008 |      0 |
| R-R34185 | K2020101500008 |      0 |
| R-R34185 | K2020101500008 |      0 |
+----------+----------------+--------+

I would like to query as follows: DISTINCT orderby, CONCAT status and COUNT status

+----------+---------------+--------------+
| orderid  | status_concat | status_count |
+----------+---------------+--------------+
| R-R34184 | 0,1,2         | 3            |
+----------+---------------+--------------+
| R-R34185 | 0             | 1            |
+----------+---------------+--------------+

I tried several codes, any subquery, grouping, but it doesn't come together. Thanks if anyone can help.

That's just group by and distinct in aggregate functions group_concat() and count() :

select orderid, 
    group_concat(distinct status order by status) status_concat, 
    count(distinct status) status_count
from mytable
group by orderid

I think you want distinct :

select orderid, group_concat(distinct status order by status), count(distinct status)
from t
group by orderid;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM