2012-08-06 63 views
0

我有兩個表使用兩組用一個select語句

  1. 日期欄的ID,年,月
  2. 交易的列編號,數量,類型,收入,儀器

類型只能是借方或貸方和儀器可以是任何方法,如信用卡等

我需要的是獲得一個查詢選擇年,月,類型,樂器和'amou nt'按類型和工具分組,按年和月分組。

我可以使用兩種不同的查詢

例如:

獲得的收入按年份和月份分組的總和:

select sum(T.income) as total 
    from transaction as T, date as D 
    where D.id = T.id 
group by D.month, D.year) 

並獲得其他值:

select D.year, D.month, 
     T.type, T.instrument, sum(T.amount) as sumAmount,T.income 
    from date as D, transaction as T 
    where D.id=T.id, 
group by T.instrument, T.type 

但我需要通過一個查詢來完成它。是否有另一種方法來檢索這個數據集?是否有可能在同一個select語句中以兩種方式使用group by?

+0

爲什麼你需要在一個聲明中做到這一點?你如何使用結果? – cegfault 2012-08-06 09:20:27

回答

2

這是你正在尋找的?

SELECT tableA.ID, tableA.`Year`, tableA.`Month`, 
     tableA.`Type`, tableA.instrument, 
     tableA.totalAmount, tableB.totalInstrument 
FROM 
(
    SELECT a.ID, a.`Year`, a.`Month`, 
      b.`Type`, b.instrument, 
      SUM(b.`amount`) totalAmount 
    FROM `date` a 
       INNER JOIN `transactions` b 
        ON a.ID = b.id 
    GROUP BY b.`Type 
) tableA 
INNER JOIN 
(
    SELECT a.ID, a.`Year`, a.`Month`, 
      b.`Type`, b.instrument, 
      SUM(b.`instrument`) totalInstrument 
    FROM `date` a 
       INNER JOIN `transactions` b 
        ON a.ID = b.id 
    GROUP BY a.`Year`, a.`Month` 
) tableB ON tableA.ID = tableB.ID AND 
      tableA.`Year` = tableB.`Year` AND 
      tableA.`Month` = tableB.`Month` 

第一子查詢是通過獲取量的總和與秒子查詢獲取儀器的總和。他們的結果將被連接起來,以獲得連續的totalAmount和totalInstrument。

+0

是這個查詢幫助。謝謝。 – user1500724 2012-08-06 10:27:18

+0

是否回答你的問題? :) – 2012-08-06 10:38:44

+0

@ user1500724:如果它回答了你的問題,你能否請John Woo的答案作爲正確的答案,所以它會幫助未來的訪問者? – 2017-08-27 15:48:58