0

我在尝试构建一个查询时遇到了很多麻烦,该查询将为我提供每个客户的姓名以及每个客户拥有的不同类型帐户的数量。这三种类型是支票、储蓄和CD。

customers:
+--------+--------+
| cid    | name   |
+--------+--------+
| 1      | a      | 
| 2      | b      |
| 3      | c      |
+--------+--------+

accounts:
+-----------+-----------+
| aid       | type      |
+-----------+-----------+
| 1         | Checkings |
| 2         | Savings   |
| 3         | Checkings |
| 4         | CD        |
| 5         | CD        |
| 6         | Checkings |
+-----------+-----------+

transactions:
+--------+--------+--------+
| tid    | cid    | aid    |
+--------+--------+--------+
| 1      | 1      | 1      |
| 2      | 1      | 2      |
| 3      | 2      | 3      |
| 4      | 3      | 4      |
| 5      | 1      | 5      |
| 6      | 3      | 4      |
| 7      | 1      | 6      |
+--------+--------+--------+

预期的答案是:

一、3

乙,1

三、1

获取名称很简单,但我如何计算每个人的帐户以及比较帐户以确保它不是同一类型?

4

2 回答 2

1

只需在DISTINCT里面添加COUNT

SELECT  a.cid, a.name, COUNT(DISTINCT c.type) totalCount
FROM    customers a
        INNER JOIN transactions b
            ON a.cis = b.cid
        INNER JOIN accounts c
            ON b,aid = c.aid
GROUP BY a.cid, a.name
于 2012-11-19T02:06:02.397 回答
0

询问:

SQLFiddle示例

SELECT 
a."name", 
COUNT(DISTINCT c."type") totalCount
FROM    customers a
        INNER JOIN transactions b
            ON a."cid" = b."cid"
        INNER JOIN accounts c
            ON b."aid" = c."aid"
GROUP BY a."cid", a."name"
ORDER BY totalCount DESC

结果:

| NAME | TOTALCOUNT |
---------------------
|    a |          3 |
|    b |          1 |
|    c |          1 |
于 2012-11-19T09:32:47.107 回答