SQL - 连接两个表,使用查询结果的自定义输出创建多个列
SQL - Join two tables, creating multiple columns with custom outputs from the result of the query
我有两张桌子。
Table 1 中的相关列如下所示:
[DateField ][H0][H1]...[H23]
2014-09-01 2 4 2
2014-09-02 3 1 4
...
2014-09-30 3 3 2
Table2 的相关列如下所示:
[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 和 Status 值都基于对应于单个日期的 Start 和 End 值。
T-Val 和 Status 字段依赖于 Start 和 End 字段,因此 H0TST 将根据 H0TST 中的 0 收集 T-Value 和 Status,具体取决于它属于哪个 Start 和 End 范围行.
在 DateField 列上连接两个表后,我应该如何构建查询的其余部分?
请帮我指明正确的方向,谢谢!
我认为聚合的 case 表达式可以满足您的需求:
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
我有两张桌子。 Table 1 中的相关列如下所示:
[DateField ][H0][H1]...[H23]
2014-09-01 2 4 2
2014-09-02 3 1 4
...
2014-09-30 3 3 2
Table2 的相关列如下所示:
[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 和 Status 值都基于对应于单个日期的 Start 和 End 值。
T-Val 和 Status 字段依赖于 Start 和 End 字段,因此 H0TST 将根据 H0TST 中的 0 收集 T-Value 和 Status,具体取决于它属于哪个 Start 和 End 范围行.
在 DateField 列上连接两个表后,我应该如何构建查询的其余部分?
请帮我指明正确的方向,谢谢!
我认为聚合的 case 表达式可以满足您的需求:
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