2017-07-16 77 views
1

我有以下簡單的表總和在MySQL

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 

我曾嘗試使用下面的查詢,但在對(BB)和對(DD)我會計算和總結兩次

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 

任何想法如何做到這一點?

回答

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 
+0

感謝那,但數量應該在每一個可以存在選擇和sum(length)相同的語句。 –

+0

@AliAlawi:我不明白你的意思。外部Select中的「count(*)」應該包含「FROM_CATEGORY = TO_CATEGORY」的行嗎? – dnoeth

+0

感謝您的幫助 –

1

修改dnoeth的回答如下

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