【问题标题】:Grouping / limiting results using multiple tables使用多个表对结果进行分组/限制
【发布时间】:2016-01-29 07:56:10
【问题描述】:

我需要显示三个表中的数据,只显示有限的链接数据。

表格示例 -
客户:客户名称、客户 ID
帐户:AccountName、AccountID、CustomerID
交易:TransactionAmount、TransactionDate、TransactionID、AccountID、CustomerID

客户可能没有任何关联的帐户,但可能有多个。 帐户可能没有任何关联的交易,但可能有多个。

显示数据有两种必需的方式:

  1. 按 TransactionDate 的前 200 笔交易,每个帐户只有一个(最近的 TransactionDate)。显示 CustomerName、AccountName、TransactionAmount。

  2. 搜索 Customername、AccountName 或 TransactionID 的结果。
    一个。如果按 CustomerName 搜索,则仅显示 CustomerName、AccountName 与最高 AccountID,以及仅使用最近的 TransactionDate 的相关 TransactionAmount。客户可能没有任何账户或交易。
    湾。如果按 AccountName 搜索,则仅使用最近的 TransactionDate 显示 CustomerName、AccountName 和相关的 TransactionAmount。客户可能没有任何交易。
    C。如果按 TransactionID 搜索,则显示 CustomerName、AccountName 和 TransactionAmount。 (这个很简单)

我无法弄清楚如何执行分组和其他聚合函数来根据需要限制数据。 任何帮助将不胜感激。

【问题讨论】:

  • 到目前为止,您创建了哪些 SQL,得到了什么结果?

标签: sql sql-server tsql


【解决方案1】:

1) 要将交易限制为最新的,您可以执行类似的操作

with LatestTransactionByAccount as (
  select * from Transactions t
  where not exists (
    select 1 from Transactions t2 where t2.AccountID = t.AccountID
    and t2.TransactionDate < t.TransactionDate)
)
select ...
from LatestTransactionByAccount
join ...

2) 类似

【讨论】:

    猜你喜欢
    • 2018-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-28
    • 1970-01-01
    • 2012-02-19
    相关资源
    最近更新 更多