如何将INNER JOIN与GROUP BY子句结合使用?

时间:2018-01-06 18:19:46

标签: sql sql-server join group-by

我有两个表,TransactionTransactionType。以下是表格的示例。

Transanction Table
+---------------+------------+--------+-------------------+
| TransactionId | CustomerId | Amount | TransactionTypeId |
+---------------+------------+--------+-------------------+
|             1 |       2743 | 21.43  |                 3 |
|             2 |       6185 | 81.38  |                 3 |
|             3 |       3157 | 32.76  |                 2 |
|             4 |       9435 | 91.75  |                 1 |
|             5 |       1853 | 17.09  |                 3 |
+---------------+------------+--------+-------------------+
TransactionType Table
+-------------------+-------------+
| TransactionTypeId | Description |
+-------------------+-------------+
|                 1 | Cash        |
|                 2 | Card        |
|                 3 | Check       |
+-------------------+-------------+

我正在寻找一种方法,可以显示TransactionTypeId表中每个Transaction的出现次数,然后JOIN显示TransactionType表,以便我可以看到描述。我试图使用这个SELECT声明:

SELECT COUNT(t.TransactionTypeId), tt.[Description]
FROM TransactionTable t
INNER JOIN TransactionType tt ON t.TransactionTypeId = tt.TransactionTypeId
GROUP BY t.TransactionTypeId
ORDER BY tt.[Description]

希望创建此结果:

+----------------------------+-------------+
| COUNT(t.TransactionTypeId) | Description |
+----------------------------+-------------+
|                          3 | Card        |
|                          1 | Cash        |
|                          1 | Check       |
+----------------------------+-------------+

然而,我收到一条错误消息," Column' TransactionType.Description'在选择列表中无效,因为它不包含在GROUP BY子句的聚合函数中。"

我究竟做错了什么。如何更改SELECT语句以达到我想要的结果?

2 个答案:

答案 0 :(得分:1)

您应该按tt.Description

进行分组
  

Group by返回一个关系/表,每个组都有一行,这个   错误是说,如果你打算使用GROUP BY子句,那么   您的SELECT语句只能选择您所在的列   在该列上分组并使用聚合函数,因为   其他列不会出现在结果表中。

SELECT COUNT(t.TransactionTypeId), tt.[Description]
FROM TransactionTable t
INNER JOIN TransactionType tt ON t.TransactionTypeId = tt.TransactionTypeId
GROUP BY tt.[Description]
ORDER BY tt.[Description]

答案 1 :(得分:0)

我假设你想要这个:每个TransactionTypeId的记录数。 所以你要把错误的列分组。您希望按TransactionTypeId进行分组,然后计算记录数(通过计算TransactionId来计算f.i)

此查询应该有效:

SELECT COUNT(t.TransactionId), tt.[Description]
FROM TransactionTable t
INNER JOIN TransactionType tt ON t.TransactionTypeId = tt.TransactionTypeId
GROUP BY tt.[Description]
ORDER BY tt.[Description]