从不同列到一个表的不同行数

时间:2013-11-22 08:49:44

标签: mysql sql group-by

我有一个填充表 book (责任),其中包括四个感兴趣的列:

text, amount, debit (account_number) , credit (account_number)

我想要列出每列(借记卡,点数,金额)中每个不同值 fi 的出现次数 oc 。我使用text-column过滤行并将出现次数设置为大于1(具有oc> 1 ):(带有'debit'的示例)。这是我的问题:

SELECT 'debit' , fi , COUNT(fi) oc FROM
    (
    SELECT debit fi, text 
    FROM book
    WHERE text
    LIKE '%Supermarket SMILE%'
) t1
GROUP BY fi
HAVING oc > 1

以下是此输出的示例(以及我在查询中使用信用额或金额替换借记时的其他两列):

+-------+------+----+    +--------+------+----+    +--------+--------+----+
| debit | fi   | oc |    | credit | fi   | oc |    | amount |  fi    | oc |
+-------+------+----+    +--------+------+----+    +--------+--------+----+
| debit |   70 |  2 |    | credit |   89 |  8 |    | amount | 136.95 |  2 |
| debit |  111 | 11 |    +--------+------+----+    | amount | 200.34 |  3 |
+-------+------+----+                              | amount | 136.95 |  2 |
                                                   +--------+--------+----+

是否可以使用MySQL中的查询将所有这些组合成一个输出? (我不再需要出现了):

+-------+--------+--------+
| debit | credit | amount |
+-------+--------+--------+
|    70 |   89   | 136.95 |
|   111 |        | 200.34 |
|       |        | 136.95 |
+-------+--------+--------+

1 个答案:

答案 0 :(得分:0)

创建一个临时表,从3个表中选择一个表。

INSERT INTO #tempTable
SELECT debit,t2.column1,t3.column1 etc ... and join on the other 2 tables and select
from those tables the columns you need as well.