2014-05-15 82 views
0

我莫名其妙地停留在一個非常簡單的任務編組行..和兩個不同的表

我有兩個表:

TABLE A: 
name time 
name1 100 
name2 50 
name1 200 
name3 100 
name2 50 

TABLE B: 
name time 
name3 100 
name1 50 
name3 200 
name2 100 
name1 50 

所有我想要的是第一個列表共有2個最高時間的名字!

像這樣的東西(但dowsn't工作OFC)

SELECT a.name 
     , SUM(a.time) as time1 
     , (SELECT SUM(time) FROM table2 b WHERE b.name = a.name GROUP BY a.name) as time2 
     , time1 + time2 as total 
FROM table1 a 
GROUP BY a.name 
ORDER BY total DESC 
LIMIT 2 

提前感謝!

+0

什麼會期望的結果集是什麼樣子?爲什麼你有兩張桌子? – Strawberry

+1

是相關的兩個表,所以你可以'加入'他們?如果不是,那麼你需要一個'union'查詢來從兩者中進行選擇,然後用一個容器查詢來完成你的'前2名'。 –

+0

@Strawberry:期望的結果應該是這樣的:1. name3 600 2. name1 400 – knzo

回答

1

我喜歡的東西去:

SELECT 
    name, 
    SUM(time) AS total_time 
    FROM (
    SELECT name, time FROM table_a 
    UNION ALL 
    SELECT name, time FROM table_b 
) AS u 
    GROUP BY name 
    ORDER BY total_time DESC 
    LIMIT 2 
; 

這裏是你的數據working sqlfiddle

+0

謝謝,但這並不正確。總和是不正確的。名字1應該有400,而不是800例如 – knzo

+0

哇,我怎麼錯過了?我糾正了我的答案,'UNION ALL'是要走的路。該方法類似於@羅布的,即使我認爲我的是一個更清潔;-) – svvac

+0

是的,謝謝。這是一個更清潔,你是對的。無論如何感謝羅布, – knzo

0

試試這個...

SELECT name, SUM(timeA + timeB) AS total 
FROM (
    SELECT name, time as timeA, 0 as timeB 
    FROM a 
    UNION ALL 
    SELECT name, 0 as timeA, time as timeB 
    FROM b 
) AS times 
GROUP BY name 
ORDER BY total DESC 
+0

非常感謝。這樣可行! – knzo