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
任何想法如何做到這一點?
感謝那,但數量應該在每一個可以存在選擇和sum(length)相同的語句。 –
@AliAlawi:我不明白你的意思。外部Select中的「count(*)」應該包含「FROM_CATEGORY = TO_CATEGORY」的行嗎? – dnoeth
感謝您的幫助 –