选择语句以在2个表之间显示正确的值

时间:2016-08-16 18:32:05

标签: sql select sql-server-2012

我有两张桌子:

Tbl_PCode:

ID : 54321
Date : 8/1/2016
PCode: REG 
Hours: 8

ID : 54321
Date : 8/1/2016
PCode: OT 
Hours: 2

Tbl_TCode:

ID : 54321
Date : 8/1/2016
TCode: InsideC 
Hours: 6

ID : 54321
Date : 8/1/2016
TCode: OutsideC 
Hours: 4

需要显示:

ID  PCode   Hours   TCode

54321 REG   6   InsideC
54321 REG   2   OutsideC
54321 OT    2   OutsideC

请帮助解决SQL语句。

1 个答案:

答案 0 :(得分:0)

如果我做得对。添加了pos列以介绍行的顺序。

with 
-- sample data
Tbl_PCode as (
    select * 
    from (values 
           (54321,cast('8/1/2016' as date), 'REG', 8, 1),
           (54321,cast('8/1/2016' as date), 'OT', 2, 2)
           ) t(ID,Date,PCode,Hours,pos) 
), 
Tbl_TCode as (
    select * 
    from (values 
           (54321,cast('8/1/2016' as date), 'InsideC', 6, 1),
           (54321,cast('8/1/2016' as date), 'OutsideC', 4, 2)
           ) t(ID,Date,TCode,Hours,pos)

), 
tally as ( 
     select top(24) rn= row_number() over(order by (select null))
     from sys.all_objects
),
-- query
t_P as (
    select *, rn=row_number() over(partition by ID,Date order by pos)  
    from Tbl_PCode
    cross apply (select top(Hours) 1 n 
                 from tally
                ) x
), 
t_T as (
    select *, rn=row_number() over(partition by ID,Date order by pos)  
    from Tbl_TCode
    cross apply (select top(Hours) 1 n 
                 from tally
                ) x
)
select t_P.ID, t_P.Date, t_P.PCode, count(*), t_T.TCode
from t_P
join t_T on t_P.ID=t_T.ID and t_P.Date=t_T.Date and t_P.rn=t_T.rn
group by t_P.ID, t_P.Date, t_P.PCode, t_T.TCode