【问题标题】:How would I create this T-SQL subquery?我将如何创建这个 T-SQL 子查询?
【发布时间】:2012-06-27 17:04:39
【问题描述】:

我在这里失去了我的感觉。在过去,我会想出一个超级 T-SQL 查询,

选择 t1.Number, t1.TransactionType, t1.Description, t1.Vendor, (Select max(t2.BatchId) From table2 t2 其中 t1.Number=t2.Number 和 t1.TransactionType=t2.TransactionType 按 t2.number,t2.transactiontype 分组)作为 BatchId 从表 1 t1

我需要 table2 中的第二列。列名为“结果”。

例子:

表格1: 编号、交易类型、描述、供应商 1、Type1、Test1、Vendor1 2、Type1、Test2、Vendor2 1、Type2、Test3、Vendor3 3、Type2、Test1、Vendor2 表2: 编号、交易类型、批次 ID、结果 1、类型1、12、错误1 1、类型1、4、错误2 1、Type2、8、成功 3、Type2、7、成功 想要的结果集: Number、TransactionType、Description、Vendor、BatchId、Result 1、Type1、Test1、Vendor1、12、error2 2、Type1、Test2、Vendor2、null、null 1、Type2、Test3、Vendor3、8、成功 3、Type2、Test1、Vendor2、7、成功

发布的查询处理前 5 列。现在最后一列怎么样?

【问题讨论】:

  • 将所需的表列添加到您的子查询 SELECT 语句中。 IE: (Select max(t2.BatchId), Result From table2 t2 ...
  • 在这种情况下,子查询不能返回多于一列。

标签: sql-server tsql inner-query


【解决方案1】:
select t1.Number, t1.TransactionType, t1.Description, t1.Vendor, t2.BatchId, t2.Result
from table1 t1
left join
(
  select t2.TransactionType, t2.number, t2.Result, t2.BatchId,
    row_number() over (partition by t2.number, t2.TransactionType order by t2.BatchId desc) as BatchNumber
  from table2 t2
) t2 on t1.Number = t2.Number
  and t1.TransactionType = t2.TransactionType
  and t2.BatchNumber = 1

如果您可以确定 t1 中的每一行在 t2 中都有相关行,那么最好将左连接替换为内连接。

UPD 在 cmets 中正确发现了一个错误。我已将查询更改为正确的版本。

【讨论】:

  • 您已使用您的语法将左连接转换为内连接。将 t.batchnumber = 1 添加到 ON 子句而不是 where 子句。 wiki.lessthandot.com/index.php/WHERE_conditions_on_a_LEFT_JOIN
  • 这成功了 oryol。不,我不能保证记录已经传送。所以结果表可能没有对应的值。左连接是完美的。
猜你喜欢
  • 2013-05-27
  • 1970-01-01
  • 1970-01-01
  • 2011-01-17
  • 1970-01-01
  • 1970-01-01
  • 2013-02-16
  • 2022-07-01
  • 1970-01-01
相关资源
最近更新 更多