【问题标题】:How can I use an INNER JOIN in conjunction with a GROUP BY clause?如何将 INNER JOIN 与 GROUP BY 子句结合使用?
【发布时间】:2018-06-16 06:14:12
【问题描述】:

我有两张桌子,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       |
+-------------------+-------------+

我正在寻找一种方法,可以在Transaction 表中显示每个TransactionTypeId 的出现次数,然后将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       |
+----------------------------+-------------+

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

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

【问题讨论】:

  • 你还必须按描述分组

标签: sql sql-server join group-by


【解决方案1】:

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

这个查询应该可以工作:

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]

【讨论】:

    【解决方案2】:

    您应该按 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]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-10
      • 2014-10-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-07
      • 1970-01-01
      • 2021-10-08
      相关资源
      最近更新 更多