Mysql - 默认情况下将行计数到一个定义的值并对它们进行分组

时间:2016-05-10 13:33:52

标签: mysql

一点帮助:我必须将一些数字计算到一个定义的值并按id分组。例如:
我的疑问:

SELECT part_number, 
NAME, 
NAME2,
count(id) as tot_prod, 
min(serial_number) as serie_min, 
max(serial_number) as serie_max, 
opt_db.Quant as qty_default
FROM my_db, opt_db  
where my_db.NAME2 = '17EM_2'  and  my_db.name2=opt_db.vs 
group by my_db.number order by my_db.SERIAL_NUMBER

my_db结果:

+-------------+-------+-------+----------+-----------+-----------+---------+
|   number    | NAME  | NAME2 | tot_prod | serie_min | serie_max | default |
+-------------+-------+-------+----------+-----------+-----------+---------+
| 312705      | 17E21 | 7EM_2 |        3 | 21895     | 21897     |       10|
| 311971      | 17E21 | 7EM_2 |       20 | 21900     | 21920     |       10|
| 311972      | 17E21 | 7EM_2 |        6 | 21925     | 21930     |       10|
+-------------+-------+-------+----------+-----------+-----------+---------+

但我想要这个 输出:

+-------------+-------+-------+-----+-------+----------+----------+--------+
|   number    | NAME  | NAME2 | tot | PACK  |serie_min |serie_max |default |
+-------------+-------+-------+-----+-------+----------+----------+--------+
| 312705      | 17E21 | 7EM_2 |   3 |  3    |  21895   | 21897    |   10   |
| 311971      | 17E21 | 7EM_2 |  20 | 10    |  21900   | 21910    |   10   |
| 311971      | 17E21 | 7EM_2 |  20 | 10    |  21911   | 21920    |   10   |
| 311972      | 17E21 | 7EM_2 |   6 |  6    |  21925   | 21930    |   10   |
+-------------+-------+-------+-----+-------+----------+----------+--------+

1 个答案:

答案 0 :(得分:0)

求助:

SELECT GROUP_CONCAT(distinct m.SERIAL_NUMBER order by m.SERIAL_NUMBER ) as series, 
            m.partnumber,
            m.NAME,
            m.NAME2,
            count(distinct m.id) as tot_prod, 
            min(m.serial_number) as serie_min, 
            max(m.serial_number) as serie_max, 
            e.Quantidade as qty_default,
            e.qty_faltam
            FROM my_db as m,  op_db  as e
            where m.NAME = 'nameExample' and  m.name2=e.name2 and m.partnumber = e.part_num
            group by m.partnumber order by series