来自MySql中UNION的总和

时间:2017-07-16 09:40:16

标签: mysql sql

我有以下简单的表格

FROM_CATEGORY      TO_CATEGORY      LENGTH
     A                 D              5
     B                 C              6
     B                 B              2
     C                 D              4
     D                 D              1

我只想得到以下结果

CATEGORY      COUNT_REPEATED      SUM_LENGTH
   A                1                5
   B                2                8
   C                2                10
   D                2                10

我试过使用下面的查询,但对于对(B B)和对(D D)我会计算和总和两次

SELECT t1.CATEGORY , COUNT(*) , SUM(t1.LENGTH)  FROM
(SELECT   FROM_CATEGORY AS CATEGORY , SUM(LENGTH) AS LENGTH FROM categoryTable GROUP BY FROM_CATEGORY
UNION ALL 
SELECT   TO_CATEGORY AS CATEGORY, SUM(LENGTH) AS LENGTH   FROM categoryTable GROUP BY TO_CATEGORY) AS t1 GROUP BY t1.CATEGORY 

知道怎么做吗?

2 个答案:

答案 0 :(得分:1)

只需过滤两个类别相同的行:

SELECT t1.CATEGORY , COUNT(*) , SUM(t1.LENGTH)
FROM
 ( SELECT   FROM_CATEGORY AS CATEGORY , SUM(LENGTH) AS LENGTH 
   FROM categoryTable
   WHERE FROM_CATEGORY <> TO_CATEGORY 
   GROUP BY FROM_CATEGORY

   UNION ALL 

   SELECT   TO_CATEGORY AS CATEGORY, SUM(LENGTH) AS LENGTH
   FROM categoryTable
   GROUP BY TO_CATEGORY) AS t1
GROUP BY t1.CATEGORY 

编辑:

根据您的评论,您希望包含FROM_CATEGORYTO_CATEGORY在您的计数中相同但不在总和中的行。然后,您需要将WHERE条件移动到CASE中并执行条件聚合

SELECT t1.CATEGORY , Count(*) , Sum(t1.LENGTH)
FROM
 ( SELECT   FROM_CATEGORY AS CATEGORY ,
      Sum(CASE WHEN  FROM_CATEGORY <> TO_CATEGORY THEN LENGTH ELSE 0 end) AS LENGTH 
   FROM categoryTable
   GROUP BY FROM_CATEGORY

   UNION ALL 

   SELECT   TO_CATEGORY AS CATEGORY, Sum(LENGTH) AS LENGTH
   FROM categoryTable
   GROUP BY TO_CATEGORY) AS t1
GROUP BY t1.CATEGORY 

答案 1 :(得分:1)

修改了dnoeth的答案,如下所示

createContainer