MYSQL查询以进行选择和分组

时间:2019-07-15 07:02:16

标签: mysql sql

我有以下MySQL表

---------------------------------
| ID_One | ID_two  | Get_val    |
---------------------------------
|   44   | 50      | 1          |
---------------------------------
|   20   | 32      | 1          |
---------------------------------
|   30   | 14      | 1          |
---------------------------------
|   50   | 44      | 2          |
---------------------------------

我想得到如下结果。

---------------------------------
| ID_One | ID_two  | **SUM_val**|
---------------------------------
|   44   | 50      | 3          |
---------------------------------
|   50   | 44      | 3          |
---------------------------------

有人可以协助完成上述查询吗? 这就是我目前正在运行的。

select ID_One,ID_Two, SUM(Get_val) 
from getList 
where ID_one='44' OR ID_two='44' 
group by ID_one, ID_two;

3 个答案:

答案 0 :(得分:1)

根据您的评论,然后将44作为user_id过滤器。 这可能对您有帮助:

SELECT ID_One,ID_two, (SELECT SUM(Get_val) FROM tplink WHERE tplink.ID_One = 44 OR tplink.ID_two = 44) as sum FROM `tplink` WHERE ID_One=44 OR ID_two = 44

enter image description here

答案 1 :(得分:1)

可能正在使用某些子查询来管理匹配的替代值

select  id_one, id_two, sum(get_val)
from (

    select  m1.ID_One, m1.ID_two, m1.getval
    from my_table m1 
    inner join  ( 
        select one, two
        from (
            select id_one one, id_two two
            from  my_table  
            union all 
            select two, id_one
            from  my_table a 
        ) t 
        group by one, two
        having count(*) > 1 
        ) t1  on t1.one = m1.id_one and t1.two = m1.id_two

    union all 

    select  m1.ID_One, m1.ID_two, m1.getval
    from my_table m1 
    inner join  ( 
        select one, two
        from (
            select id_one one, id_two two
            from  my_table  
            union all 
            select two, id_one
            from  my_table a 
        ) t 
        group by one, two
        having count(*) > 1 
        ) t1  on t1.two = m1.id_one and t1.one = m1.id_two
)  t2 
group by id_one, id_two

答案 2 :(得分:1)

如果我的理解正确,那么您基本上需要所有SUM()值中的Get_val,其中ID_OneID_Two 44 。然后,您要显示ID_OneID_Two的所有唯一组合以及“总和”。

我们可以在Derived Table中获得“总和”;然后CROSS JOIN将其返回到主表,以获取所需的行:

SELECT 
  DISTINCT t.ID_One, t.ID_Two, dt.tot_sum 
FROM getList AS t 
CROSS JOIN 
(
  SELECT SUM(Get_val) AS tot_sum 
  FROM getList 
  WHERE ID_One = '44' OR ID_Two = '44'
) AS dt 
WHERE t.ID_One = '44' OR t.ID_Two = '44'

结果

| ID_One | ID_Two | tot_sum |
| ------ | ------ | ------- |
| 44     | 50     | 3       |
| 50     | 44     | 3       |

View on DB Fiddle