使用说明更新活动列

时间:2019-05-07 01:14:57

标签: sql-server

我有两个表:

学生活动表:

ID  NAME    TIME_FROM   TIME_TO    ACTIVITY
-------------------------------------------
1   ABC      9:00        10:00     WALK
2   ABC      10:00       12:00     PLAY

GAMELOG table:

ID ACTIVITY_ID   STUDENT_NAME  CRICKET (HR)   FOOT BALL (HR)
------------------------------------------------------------------
 1    2            ABC              1               1

学生活动表具有学生的主要活动,而游戏日志表包含详细的活动。例如:活动“ PLAY”包括板球和脚球作为活动的详细信息。

我需要一个查询来检索活动详细信息,如预期输出所示:

ID  NAME    ACTIVITY    DURATION HOURS  
----------------------------------------
1   ABC     WALKING          1  
2   ABC     CRICKET          1  
2   ABC     FOOTBALL         1

如果没有如上图所示的WALKING中的主要活动的详细活动,则查询应返回主要活动

假定游戏日志是根据记录的时间生成的。学生走了一个小时,玩了2个小时。比赛的详细信息被记录为板球1个小时和足球1个小时

游戏顺序应为1.板球和2.脚球

为简单起见,每当有一个列值PLAY时,输出就应显示GameLog表中的游戏详细信息以及CRICKET和FOOT BALL TIME。

2 个答案:

答案 0 :(得分:0)

我尝试了没有实际创建表的情况。希望对您有所帮助。

SELECT 
    S.ID
    ,S.Name
    ,CASE 
        WHEN S.Activity = 'WALK' THEN 'Walking'
        WHEN A.Cricket = 1 AND S.Activity = 'Play' THEN 'Cricket'
        WHEN A.Football = 1 AND S.Activity = 'Play' THEN 'Football'
    END CASE AS Activity
FROM 
    Student_Activity SA 
    JOIN GameLog G ON SA.Name = G.Student_Name

答案 1 :(得分:0)

根据您的选择尝试先将Gamelog转换为CTE或临时表

with game_cte as
Select 
    id
    ,activity_id
    ,Student_Name
    ,'Cricket' as Activity
    ,cricket_hr as duration
    ,'Play' as action
from
    gamelog
where
    cricket_hr > 0

UNION ALL

Select 
    id
    ,activity_id
    ,Student_Name
    ,'Football' as Activity
    ,football_hr as duration
    ,'Play' as action
from
    gamelog
where
    football_hr > 0

然后尝试该联合

SELECT 
    G.activity_id
    ,G.Name
    ,G.Activity
    ,G.duration
FROM 
    Student_Activity SA 
    JOIN game_cte G ON SA.Name = G.Student_Name and SA.activity = G.action

UNION ALL

SELECT 
    S.ID
    ,S.Name
    ,CASE 
        WHEN S.Activity = 'WALK' THEN 'Walking'
     END CASE AS Activity
    ,(time_to - time_from) as duration
FROM 
    Student_Activity SA 
    JOIN GameLog G ON SA.Name = G.Student_Name
WHERE
    sa.activity = 'Walk'

尝试是否有帮助。