0

我有两张桌子:

查找表 ( tabOne):

    KEY  |  Group  |  Name  |  Desc  | Val_Key
    ----------------------------------------
     1   |     a   | NameA  | DescA  |  10
     2   |     b   | NameB  | DescB  |  20
     3   |     c   | NameC  | DescC  |  30
     4   |     d   | NameD  | DescD  |  40
     5   |     e   | NameE  | DescE  |  50
     6   |     f   | NameF  | DescF  |  60

第二个表格包含读数 ( tabTwo):

    KEY  |  Date  |  Reading  | Val_Key
    ----------------------------------------
     1   |  Date   | Read     |  10
     2   |  Date   | Read     |  20
     3   |  Date   | Read     |  40
     4   |  Date   | Read     |  40
     5   |  Date   | Read     |  30
     6   |  Date   | Read     |  20
     7   |  Date   | Read     |  40
     8   |  Date   | Read     |  20
     9   |  Date   | Read     |  10
     10  |  Date   | Read     |  20
     11  |  Date   | Read     |  50
     12  |  Date   | Read     |  60

我需要做的是加入tabTwoTabOne创建一个包含最新阅读的列和一个包含最旧阅读的列TabOne

归根结底,我想要一张如下所示的表格:

    KEY  |  Group  |  Name  |  Desc  | Val_Key | LastReading | FirstReading |
    -------------------------------------------------------------------------
     1   |     a   | NameA  | DescA  |  10     |             |              |   
     2   |     b   | NameB  | DescB  |  20     |             |              |
     3   |     c   | NameC  | DescC  |  30     |             |              |
     4   |     d   | NameD  | DescD  |  40     |             |              |
     5   |     e   | NameE  | DescE  |  50     |             |              |
     6   |     f   | NameF  | DescF  |  60     |             |              |

谢谢!房地美

4

2 回答 2

1

如果这是 Sql Server 2005 或更新版本,则外部应用将有所帮助:

select TabOne.*, 
       last.Reading LastReading, 
       first.Reading FirstReading
from TabOne
outer apply
(
  select top 1
         Reading
    from TabTwo
   where TabTwo.Val_Key = TabOne.val_Key
  order by TabTwo.Date desc
) last
outer apply
(
  select top 1
         Reading
    from TabTwo
   where TabTwo.Val_Key = TabOne.val_Key
  order by TabTwo.Date asc
) first

现场测试是@Sql Fiddle

于 2012-05-24T14:10:22.530 回答
0

如果子查询直接移动到主查询的 SELECT 子句,则@Nikola Markovinović 的解决方案可以更普遍适用,这可能每个子查询只检索一个值,因此作为标量表达式有效:

SELECT
  t1.[KEY],
  t1.[Group],
  t1.Name,
  t1.[Desc],
  t1.Val_Key,
  (
    SELECT TOP 1 Reading
    FROM TabTwo
    WHERE Val_Key = t1.Val_Key
    ORDER BY Date DESC
  ) AS LastReading,
  (
    SELECT TOP 1 Reading
    FROM TabTwo
    WHERE Val_Key = t1.Val_Key
    ORDER BY Date ASC
  ) AS FirstReading
FROM TabOne t1

如果您需要沿途约会,您可能不得不坚持 Nikola 的解决方案。有一个替代方案,但它更麻烦(尽管也更标准):它将涉及对TabTwo的数据进行分组Val_Key以获取每个 的最早/最新日期Val_Key,然后加入TabTwo以访问与找到的日期相对应的整行以最终拉出必要的列,并最终连接两个结果集以TabOne获得最终的列集。

于 2012-05-25T10:00:04.490 回答