过滤数据库表

时间:2018-08-24 08:47:03

标签: mysql database

我有一个如下表

  |-----|-----|--------|
  | id  | num | amount |
  |-----|-----|--------|
  | 101 | a   |     10 |      
  | 102 | a   |      6 |   
  | 102 | a   |      3 |
  | 101 | b   |      5 |
  | 101 | a   |     10 |
  | 101 | b   |      5 |           
  |-----|-----|--------|

我要显示的是

  |---------------------|------------------|---------------------|
  |        id           |     num          |        amount       |
  |---------------------|------------------|---------------------|
  |       101           |       a,b        |          5          |        
  |---------------------|------------------|---------------------|

即,如果num表中的两个不同值具有相同的id,则将它们的数量相加并除以3,然后丢弃其他值。如何使用mysql实现此目标?如果同样的数据也重复两次,则只有一次重复发生,然后再消除一次

我尝试过

SELECT id, GROUP_CONCAT(DISTINCT num) AS nums, SUM(amount) / 3 AS amount
FROM table1
GROUP BY id
HAVING COUNT(DISTINCT num) > 1

但是它会计算两个值,即数量是10而不是5。

2 个答案:

答案 0 :(得分:0)

您可以使用一个子查询来进行区分,并与ID进行连接,其ID的计数> 1

  select  t1.id, GROUP_CONCAT( t1.num) AS nums, SUM(t1.amount) / 3 AS amount
  from (
     select distinct  id, num, amount
     from table1  
     group by id, num
  ) t1
  INNER JOIN (
    select id, num, count(*)
    from table1
    group by id, num 
    having count(*)>1 

  ) t2 on t2.id = t1.id

答案 1 :(得分:0)

这是一个复杂的问题,因为表中没有自然排序。因此,我们必须通过为表中的每个条目生成行号来创建人工排序。我们通过以下查询来做到这一点:

SELECT @rownum1 := @rownum1 + 1 AS rownum, id, num, amount
FROM table1
JOIN (SELECT @rownum1 := 0) r

这将提供以下输出:

rownum  id      num     amount
1       101     a       10
2       102     a       6
3       102     a       3
4       101     b       5
5       101     a       3
6       101     b       5

完成此操作后,我们现在可以为idnum的每种组合选择一组值,它们代表表中的“第一个”条目:

SELECT id, num, MIN(rownum) AS rownum
FROM (SELECT @rownum2 := @rownum2 + 1 AS rownum, id, num, amount
      FROM table1
      JOIN (SELECT @rownum2 := 0) r
      ) t
GROUP BY id, num;

输出:

id      num     rownum
101     a       1
101     b       4
102     a       2

现在我们有了该信息,我们可以JOIN对信息进行排序,然后对结果集使用原始查询来获取每组值的“第一个”出现的结果:< / p>

SELECT t1.id, GROUP_CONCAT(DISTINCT t1.num) AS nums, SUM(t1.amount) / 3 AS amount
FROM (SELECT @rownum1 := @rownum1 + 1 AS rownum, id, num, amount
      FROM table1
      JOIN (SELECT @rownum1 := 0) r
      ) t1
JOIN (SELECT id, num, MIN(rownum) AS rownum
      FROM (SELECT @rownum2 := @rownum2 + 1 AS rownum, id, num, amount
            FROM table1
            JOIN (SELECT @rownum2 := 0) r
            ) t
      GROUP BY id, num) t2
    ON t1.rownum = t2.rownum
GROUP BY t1.id
HAVING COUNT(DISTINCT t1.num) > 1;

输出:

id      nums    amount
101     a,b     5

SQLFiddle