我有两张桌子:
查找表(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
我需要做的是与tabTwo
一起加入TabOne
并创建一个包含最新阅读的列和一个包含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 | | |
谢谢! 房地
答案 0 :(得分:1)
如果这是Sql Server 2005或更新版本,outer apply将有所帮助:
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
答案 1 :(得分:0)
@Nikola Markovinović's solution可以更普遍适用,这可能每个子句只检索一个值,因此有效作为标量表达式:
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
如果您需要,例如沿途的日期,你可能不得不坚持尼古拉的解决方案。有一个替代方案,但它更麻烦(虽然更标准):它将涉及TabTwo
的{{1}}数据分组,以获得每Val_Key
个最早/最晚的日期,然后加回Val_Key
以访问与找到的日期对应的整行,最后拉出必要的列,最终将两个结果集合并到TabTwo
以获得最终的列集。