我有两张桌子。 表1中的相关列如下所示:
[DateField ][H0][H1]...[H23]
2014-09-01 2 4 2
2014-09-02 3 1 4
...
2014-09-30 3 3 2
表2的相关栏目如下:
[DateField ][Start][End][T-Val][Status]
2014-09-01 0 4 1 Off
2014-09-01 5 18 2 Low
2014-09-01 19 23 1 Off
2014-09-02 0 10 1 Off
2014-09-02 11 20 2 Med
2014-09-02 21 23 1 Off
...
我需要输出像......
[DateField ][H0][H1]...[H23][H0TST][H1TST]...[H12TST]...[H23TST]
2014-09-01 2 4 2 1_Off 1_Off 2_Low 1_Off
2014-09-02 3 1 4 1_Off 1_Off 2_Med 1_Off
...
在另外24列的情况下,每列都有T-Val和列中的状态值,基于与单个日期对应的开始和结束值。
T-Val和Status字段取决于Start和End字段,这样H0TST将根据H0TST中的0收集T值和状态,具体取决于它所属的开始和结束范围行。 / p>
在DateField列上加入两个表之后,我该如何构建查询的其余部分?
请指点我正确的方向,谢谢!
答案 0 :(得分:3)
我认为聚合的案例表达式会为您提供所需的内容:
select t1.*,
h0tst = max(case when t1.H0 between t2.start and t2.[end] then concat([T-Val],'-', status) end),
h1tst = max(case when t1.H1 between t2.start and t2.[end] then concat([T-Val],'-', status) end),
h23tst = max(case when t1.H23 between t2.start and t2.[end] then concat([T-Val],'-', status) end )
from table1 t1
join table2 t2 on t1.DateField = t2.DateField
group by t1.DateField, t1.H0, t1.H1, t1.h23
这将产生如下输出:
DateField H0 H1 H23 h0tst h1tst h23tst
2014-09-01 2 4 2 1-Off 1-Off 1-Off
2014-09-02 3 1 4 1-Off 1-Off 1-Off