简体   繁体   English

如何在连接两个表的同时从第二个表获取前1行:SQL Server 2014

[英]How to get the top 1 row from second table while joining two tables : SQL Server 2014

I am new to SQL Server 2014. I am trying to get data from two tables by join. 我是SQL Server 2014的新手。我试图通过连接从两个表中获取数据。

In the second table, I have multiple values for the same Header ID. 在第二张表中,我具有相同标题ID的多个值。 I want to take the TOP 1 row value from the second table: 我想从第二张表中获取TOP 1行值:

在此处输入图片说明

在此处输入图片说明

I want to take the data as in the following format 我想采用以下格式获取数据

在此处输入图片说明

I want to take the TOP 1 image for all the names in the first table. 我要为第一张表中的所有名称拍摄TOP 1图像。

Can anyone help me to solve this? 谁能帮我解决这个问题?

You can use cross apply . 您可以使用cross apply The conditions are a little unclear, but the idea is: 条件还不清楚,但是想法是:

select t1.*, t2.images
from table1 t1 cross apply
     (select top (1) t2.*
      from t2
      where t2.? = t1.id
     ) t2;

I would speculate that the correlated condition should use either t2.h_id or t2.id . 我推测相关条件应使用t2.h_idt2.id

Is that what are you looking for 那是你在找什么

WITH T1 AS
(
  SELECT 1 ID,
         'Anto' Name,
         'Manager' Position
  UNION
  SELECT 2, 
         'Nick',
         'CEO'
)
, T2 AS
(
  SELECT 1 ID,
         1 H_ID,
         'URL1' Images
  UNION
  SELECT 2,
         1,
         'URL2'
  UNION
  SELECT 3,
         1,
         'URL3'
)

SELECT *
FROM T1 CROSS JOIN (SELECT TOP 1 Images FROM T2 ORDER BY ID) TT

Demo 演示版

OR 要么

SELECT TOP 1
       T1.*,
       T2.Images
FROM T1 INNER JOIN T2
ON T1.ID = T2.H_ID
ORDER BY T2.ID;

Try this one 试试这个

SELECT *
FROM T1, T2
WHERE T1.ID = T2.H_ID
AND NOT EXISTS(
    SELECT * 
    FROM T2 as T2BIS -- just an alias table
    WHERE T2BIS.H_ID = T1.ID -- usual join
    AND T2.ID > T2BIS.ID --change operator to take the last instead of the first
)

This is a generic solution that you can use in many case when you adjust the subquery on where conditions and EXISTS / NOT EXISTS clause, just an camparison between two identical spaces, you define the conditions. 这是一个通用的解决方案,当您在条件和EXISTS / NOT EXISTS子句(仅两个相同空间之间的分隔)定义条件时调整子查询时,可以在许多情况下使用。

  1. the first of something ... 首先是...
  2. the last of someting ... 最后的东西...
  3. everything higher than ... 一切都高于...
  4. etc... 等等...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM