mysql,计算两个表之间的不同值(V2)

时间:2019-04-26 18:30:20

标签: mysql group-by count

我有两个表:

CREATE TABLE TableA  
(ID_A INT,   
 P1 INT,
 P2 INT,
 P3 INT,
 P4 INT,
 Nr1 INT,
 Nr2 INT,
 Nr3 INT,
 Nr4 INT);

INSERT INTO TableA VALUES
(1,3,4,3,5,2,3,1,4),
(2,5,4,3,4,1,1,1,2);

CREATE TABLE TableB
(ID_B INT,
NAME TEXT);

INSERT INTO TableB VALUES
(1,"A"),
(2,"B"),
(3,"C"),
(4,"D"),
(5,"E"),
(6,"F");

表中的值

TableA
+------+----+----+----+-----+----+----+----+-----+
| ID_A | P1 | P2 | P3 | P4  | Nr1| Nr2| Nr3| Nr4 |
+------+----+----+----+-----+----+----+----+-----+
|    1 |  3 |  4 |  3 |   5 |  2 |  3 |  1 |  4  |
|    2 |  5 |  4 |  3 |   4 |  1 |  1 |  1 |  2  |
+------+----+----+----+-----+----+----+----+-----+

TableB
+------+------+
| ID_B | Name |
+------+------+
|    1 | A    |
|    2 | B    |
|    3 | C    |
|    4 | D    |
|    5 | E    |
|    6 | F    |
+------+------+

tableA P1 = TableB ID_B

tableA P2 = TableB ID_B

tableA P3 = TableB ID_B

tableA P4 = TableB ID_B

我想要表B中与P1,P2,P3,P4对应的所有名称的总和;而Nr1,Nr2,Nr3,Nr4是数量:

P1 =总和Nr1

P2 =总和Nr2

P3 = Sum Nr3

P4 =总和Nr4

我想要这个:

+----------+------+
| COUNT(*) | Name |
+----------+------+
|        4 | C    |
|        6 | D    |
|        5 | E    |
+----------+------+

My DEMO db-fiddle.com

该演示未加Nr。

感谢那些会帮助我的人。

3 个答案:

答案 0 :(得分:1)

在提琴中,您没有选择相应的Nr1 / 2/3/4值。将它们添加到select子句中并对它们求和:

SELECT Name, SUM(Val)
FROM (
    SELECT TableB.Name, TableA.Nr1 AS Val FROM TableA JOIN TableB ON TableA.P1 = TableB.ID_B UNION ALL
    SELECT TableB.Name, TableA.Nr2 AS Val FROM TableA JOIN TableB ON TableA.P2 = TableB.ID_B UNION ALL
    SELECT TableB.Name, TableA.Nr3 AS Val FROM TableA JOIN TableB ON TableA.P3 = TableB.ID_B UNION ALL
    SELECT TableB.Name, TableA.Nr4 AS Val FROM TableA JOIN TableB ON TableA.P4 = TableB.ID_B
) AS x
GROUP BY Name

答案 1 :(得分:1)

或者,如果您想要执行此操作而无需子查询:

  SELECT Name, 
         SUM(IF(P1 = ID_B, Nr1, 0) +
             IF(P2 = ID_B, Nr2, 0) +
             IF(P3 = ID_B, Nr3, 0) +
             IF(P4 = ID_B, Nr4, 0))
    FROM TableA
    JOIN TableB ON (TableA.P1 = TableB.ID_B
                    OR TableA.P2 = TableB.ID_B
                    OR TableA.P3 = TableB.ID_B
                    OR TableA.P4 = TableB.ID_B)
GROUP BY Name;

答案 2 :(得分:0)

您可以使用选择的UNION ALL并按

分组
  select t2.name, count(*)
  from TableB t2
  inner join  (
  select  p1 p 
  from TableA 
  union all 
  select  p2
  from TableA 
  union all 
  select  p3
  from TableA 
  union all 
  select  p4
  from TableA 
  ) t on t.p = t2.ID_B
  group t2.name
  order by count(*) desc