5

私は2つのテーブルを持っています

  1. 列ID、年、月のある日付
  2. 列ID、金額、タイプ、収入、商品のトランザクション

タイプはデビットまたはクレジットのいずれかであり、商品はクレジットカードなどの任意の方法です。

必要なのは、年、月、タイプ、商品、タイプと商品でグループ化された「金額」の合計、および年と月でグループ化された収入の合計を選択するクエリを取得することです。

2つの異なるクエリを使用して値を取得できます

例:

年と月でグループ化された収入の合計を取得するには:

  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ステートメントでgroupbyを2つの方法で使用することは可能ですか?

4

1 に答える 1

10

これはあなたが探しているものですか?

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`

最初のサブクエリは金額の合計を取得し、2 番目のサブクエリはインストゥルメントの合計を取得します。totalAmount と totalInstrument を連続して取得するために、それらの結果が結合されます。

于 2012-08-06T09:30:37.923 に答える